From ff95d971397d6bb29fabac14c924a6549b6241c3 Mon Sep 17 00:00:00 2001 From: sudoHG Date: Mon, 16 Nov 2026 09:47:32 +0800 Subject: [PATCH 1/4] Give the iPhone app Requests, History and Macs tabs (#346) The iPhone app opens to three tabs in the system TabView, each with its own navigation stack and large title. Requests lists only requests that can still be decided or wait for the Mac, with banners for iCloud and notifications turned off and empty states for no Mac and no request; its badge counts the requests that can still be decided. A notification for the app in front shows as a banner and never opens the request's page; the new row is highlighted instead. History shows its empty state until #349. Macs lists the Macs with a + to pair, this iPhone's iCloud, notification and delivery-check status, the version and the removal notice. Mac detail becomes a grouped list with #342's wording unchanged. Notification authorization is read through the environment at launch, after the welcome's prompt and whenever the scene becomes active. The tab screens are drawn as SwiftUI stacks so the renders use the real views; the render tests draw stand-ins for the system chrome. --- docs/features.md | 2 +- iOS/AskKeyiOSKit/App/AppModel+Macs.swift | 68 +++ iOS/AskKeyiOSKit/App/AppModel.swift | 12 + iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift | 11 +- .../Resources/Localizable.xcstrings | 507 +++++++++++++++++- .../Services/AppEnvironment.swift | 13 + iOS/AskKeyiOSKit/Services/LiveServices.swift | 8 + iOS/AskKeyiOSKit/Views/Components.swift | 226 ++++++++ iOS/AskKeyiOSKit/Views/HistoryView.swift | 25 + iOS/AskKeyiOSKit/Views/MacDetailView.swift | 132 +++-- iOS/AskKeyiOSKit/Views/MacsView.swift | 242 +++++++++ iOS/AskKeyiOSKit/Views/PairedMacsView.swift | 208 ------- iOS/AskKeyiOSKit/Views/RequestCardView.swift | 15 - iOS/AskKeyiOSKit/Views/RequestsView.swift | 230 ++++++++ iOS/AskKeyiOSKit/Views/RootView.swift | 85 ++- iOS/AskKeyiOSKitTests/Fakes/FakeSystem.swift | 11 + iOS/AskKeyiOSKitTests/HomeTests.swift | 153 ++++++ iOS/AskKeyiOSKitTests/RenderChrome.swift | 114 ++++ iOS/AskKeyiOSKitTests/ScreenRenderTests.swift | 126 +++-- scripts/build-ios.sh | 2 +- 20 files changed, 1850 insertions(+), 340 deletions(-) create mode 100644 iOS/AskKeyiOSKit/Views/HistoryView.swift create mode 100644 iOS/AskKeyiOSKit/Views/MacsView.swift delete mode 100644 iOS/AskKeyiOSKit/Views/PairedMacsView.swift create mode 100644 iOS/AskKeyiOSKit/Views/RequestsView.swift create mode 100644 iOS/AskKeyiOSKitTests/HomeTests.swift create mode 100644 iOS/AskKeyiOSKitTests/RenderChrome.swift diff --git a/docs/features.md b/docs/features.md index 3277a9ee..b9142c0f 100644 --- a/docs/features.md +++ b/docs/features.md @@ -207,7 +207,7 @@ Stage 2 and stage 4 of the multi-device roadmap ([#269](https://github.com/sudoH | iPhone approver | Pairing an iPhone makes it an approver (ADR 0014 as amended by #336); there is no separate switch or code, and removing the pairing on either device ends it. Read requests go to approvers at once while the Mac is locked or its lock state is unknown, otherwise after 20 seconds without a decision or when it locks; the first decision wins; Allow needs Face ID or Touch ID and Deny does not; writes, organize operations and group allowances stay on the Mac. | **Keep** | `Sources/AskKeyDevices/Pairing/PairingSession.swift`
`Sources/AskKeyVault/Vault+Devices.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteApproval.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator+RemoteDecisions.swift`
`Sources/AskKeyDevices/Approval/ApprovalRequest.swift`
`iOS/AskKeyiOSKit/Approvals/RequestCard.swift` | `Tests/AskKeyDevicesTests/PairingApproverTests.swift`
`Tests/AskKeyVaultTests/DeviceApproverFlagTests.swift`
`Tests/AskKeyAppTests/RemoteApprovalPairingTests.swift`
`Tests/AskKeyAppTests/RemoteApprovalSendingTests.swift`
`Tests/AskKeyAppTests/RemoteApprovalDecisionTests.swift`
`Tests/AskKeyDevicesTests/ApprovalVectorTests.swift`
`iOS/AskKeyiOSKitTests/ApprovalDecisionTests.swift` | | What leaves the Mac | Until someone chooses **Pair a Device…**, update checks stay the only outbound requests: no identity, no CloudKit request, no push registration. Once the identity exists, until a local erase, the App uses the iCloud account's private CloudKit database and Apple's push service, sending routing data and end-to-end encrypted messages. A remote request carries the requester's name and purpose (not verified), the credential's name, the command line, the working directory, the executable's name, the delivered variable names with a bundle's component names, the deadline, the offers, the Mac App's launch time, a response ID and a binding digest; never a credential value, a component's content, file contents, inherited environment, write payload, the vault key, anything about Hidden credentials or the Mac's name. | **Keep** | `Sources/AskKeyAppKit/App/AppDelegate+Devices.swift`
`Sources/AskKeyAppKit/Devices/DeviceCoordinator.swift`
`Sources/AskKeyDevices/Approval/ApprovalRequestDisplay.swift`
`Sources/AskKeyDevices/CloudKit/CloudKitDeviceTransport.swift`
`scripts/build-app.sh` | `Tests/AskKeyAppTests/DeviceCoordinatorDevicesTests.swift`
`Tests/AskKeyAppTests/RemoteApprovalSendingTests.swift`
`Tests/AskKeyDevicesTests/ApprovalPayloadTests.swift`
`Tests/Automation/test_build_app_cloudkit.py` | | iPhone notifications | The notification extension shows the card sentence (requester, the iPhone's name for the Mac, credential and executable name) only for a request it fetched, decrypted and verified from a Mac the iPhone approves for, and generic text otherwise; never a credential value, arguments, the working directory or variable names. Show Previews decides what the Lock Screen shows, and Notification Center keeps them until removed. Ask Key never asks the person to act on a notification's text. | **Keep** | `iOS/AskKeyiOSNotificationService/Sources/NotificationProcessor.swift`
`iOS/AskKeyiOSNotificationService/Sources/NotificationText.swift`
`Sources/AskKeyDevices/Approval/DeviceMessageVerifier.swift` | `iOS/AskKeyiOSNotificationService/Tests/NotificationProcessorTests.swift`
`iOS/AskKeyiOSNotificationService/Tests/NotificationContentTests.swift` | -| iPhone home | The iPhone app has three tabs: Requests (requests that can still be decided or wait for the Mac, with a badge counting those that can still be decided), History and Macs (the paired Macs, pairing, and this iPhone's iCloud, notification, delivery-check and version status). A finished request moves to History once its open page is closed, or at once if its page was closed; a request arriving while the app is open shows a banner and never opens its page by itself; a page opened from a notification shows a placeholder without content, never the notification's text, until the app has verified the request. Specified in ADR 0014 as amended by #345 and built by #346, #347 and #348, which update this row's files. | **Keep** (planned) | `iOS/AskKeyiOSKit/Views/RootView.swift`
`iOS/AskKeyiOSKit/Views/PairedMacsView.swift`
`iOS/AskKeyiOSKit/Views/RequestCardView.swift` | `iOS/AskKeyiOSKitTests/ScreenRenderTests.swift` | +| iPhone home | The iPhone app has three tabs: Requests (requests that can still be decided or wait for the Mac, with a badge counting those that can still be decided), History and Macs (the paired Macs, pairing, and this iPhone's iCloud, notification, delivery-check and version status). A finished request moves to History once its open page is closed, or at once if its page was closed; a request arriving while the app is open shows a banner and never opens its page by itself; a page opened from a notification shows a placeholder without content, never the notification's text, until the app has verified the request. Specified in ADR 0014 as amended by #345. #346 built the tabs, the badge, the banners and the foreground banner; #347 and #348 build the request page's outcomes and the opening states and update this row's files. | **Keep** (planned) | `iOS/AskKeyiOSKit/Views/RootView.swift`
`iOS/AskKeyiOSKit/Views/RequestsView.swift`
`iOS/AskKeyiOSKit/Views/HistoryView.swift`
`iOS/AskKeyiOSKit/Views/MacsView.swift`
`iOS/AskKeyiOSKit/Views/MacDetailView.swift`
`iOS/AskKeyiOSKit/Views/Components.swift`
`iOS/AskKeyiOSKit/Views/RequestCardView.swift`
`iOS/AskKeyiOSKit/App/AppModel+Macs.swift`
`iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift` | `iOS/AskKeyiOSKitTests/HomeTests.swift`
`iOS/AskKeyiOSKitTests/ScreenRenderTests.swift` | | iPhone history | The iPhone keeps a summary of each request its app verified, for 30 days after the request ends (deleted the next time the app runs after that) and at most 500 entries with the oldest dropped first: the requester, the credential, the executable's name, the iPhone's name for the Mac at the time, the received and ended times and the outcome, plus identifiers and this iPhone's decision; never the command line, the working directory, the delivered names, the purpose or any credential value. The file is encrypted under a this-device-only keychain key, has the request store's data protection, is bound to the iCloud account, excluded from backups and out of the notification extension's reach. Opening it needs no Face ID or Touch ID; **Clear All History** deletes it; removing a Mac keeps its entries until they age out; an account change, sign-out or restriction and an identity reset delete it. It lists only requests this app verified; the Mac's access records stay the complete record. Specified in ADR 0014 as amended by #345; #349 builds it and replaces this row's files. | **Keep** (planned) | `docs/adr/0014-remote-approval.md` | Added by #349 | ## Fixed removals diff --git a/iOS/AskKeyiOSKit/App/AppModel+Macs.swift b/iOS/AskKeyiOSKit/App/AppModel+Macs.swift index 76eb241c..81aa5056 100644 --- a/iOS/AskKeyiOSKit/App/AppModel+Macs.swift +++ b/iOS/AskKeyiOSKit/App/AppModel+Macs.swift @@ -90,3 +90,71 @@ extension AppModel { } } } + +/// The home's three tabs (ADR 0014 → iPhone app, Home, amended by #345). +public enum HomeTab: Hashable, Sendable, CaseIterable { + /// Requests that can still be decided or wait for the Mac. + case requests + /// Requests this app verified, once they ended (#349). + case history + /// The paired Macs, pairing and this iPhone's own status. + case macs +} + +/// What the home shows besides the Macs: the Requests tab's rows and badge, +/// the notification authorization and the last delivery check. +extension AppModel { + // MARK: Home + + /// The Requests tab's rows: requests that can still be decided or wait + /// for the Mac. A finished request leaves the tab (decision 7 of #344); + /// its open page keeps showing it until the person closes the page. + public func activeRequests(at now: Date) -> [RequestCard] { + requests.filter { !$0.phase(at: now).isFinished } + } + + /// The Requests tab's badge: the requests that can still be decided. + public func decidableRequestCount(at now: Date) -> Int { + requests.filter { $0.phase(at: now) == .pending }.count + } + + /// When the badge can next change without a new card: each undecided + /// request's countdown end. + public var decidableCountChanges: [Date] { + requests.filter { $0.decision == nil && $0.outcome == nil && !$0.isGone }.map(\.countdownEnd).sorted() + } + + /// The Macs whose requests this iPhone accepts. + public var approvingMacCount: Int { + pairedMacs.filter(\.isApprover).count + } + + /// Notifications are off for Ask Key, so a request arrives unannounced. + public var notificationsOff: Bool { + notificationAuthorization == .denied + } + + /// When this iPhone last answered a delivery check; nil before the first. + public var lastDeliveryCheck: Date? { + deliveryRecords.map(\.arrivedAt).max() + } + + /// The scene became active: read the notification authorization again, + /// since the person may have changed it in Settings, then collect the + /// pushes and process the inbox. + public func sceneBecameActive() async { + await refreshNotificationAuthorization() + await becameActive() + } + + func refreshNotificationAuthorization() async { + notificationAuthorization = await environment.notifications.authorization() + } + + func readBiometryKind() { + switch environment.biometry.status() { + case .enrolled(let kind), .notEnrolled(let kind), .deniedForApp(let kind): biometryKind = kind + case .passcodeNotSet, .unavailable: break + } + } +} diff --git a/iOS/AskKeyiOSKit/App/AppModel.swift b/iOS/AskKeyiOSKit/App/AppModel.swift index 0f145294..b79c4077 100644 --- a/iOS/AskKeyiOSKit/App/AppModel.swift +++ b/iOS/AskKeyiOSKit/App/AppModel.swift @@ -33,6 +33,15 @@ public final class AppModel { public internal(set) var opening: OpeningRequest? /// A newly paired Mac got a numbered name; the person may rename it. public var renamePrompt: RenamePrompt? + /// The home's tab. A request that arrives never changes it (ADR 0014 → + /// iPhone app, Finished and arriving requests). + public var selectedTab: HomeTab = .requests + /// Whether Ask Key may show notifications, as last read: at launch, + /// after the welcome's prompt and whenever the app becomes active; nil + /// until the first read. + public internal(set) var notificationAuthorization: NotificationAuthorization? + /// Face ID or Touch ID, for the Requests tab's footnote. + public internal(set) var biometryKind: BiometryKind = .faceID @ObservationIgnored let environment: AppEnvironment @ObservationIgnored var services: DeviceServices? @@ -140,6 +149,7 @@ public final class AppModel { let token = environment.localState.inboxPosition?.token.map(InboxChangeToken.init(data:)) await activate(makeServices(identity: identity, transport: transport, inboxToken: token)) await environment.notifications.registerAtLaunch() + await refreshNotificationAuthorization() } /// The services with this model as the approver: the handler of @@ -163,6 +173,7 @@ public final class AppModel { // Loaded before anything can suspend, so a request handled while // the stored ones are opened again is added to them, not lost. loadApprovals() + readBiometryKind() adoptEarlyPushes(for: services.deviceID) stage = .ready watchAccount() @@ -260,6 +271,7 @@ public final class AppModel { case .temporarilyUnavailable: return .iCloudUnavailable } await environment.notifications.requestAuthorizationAndRegister() + await refreshNotificationAuthorization() let deviceID = DeviceID(messagePublicKey: setup.identity.messagePublicKey) if !setup.stored { do { diff --git a/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift b/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift index 5678da46..d57d81a7 100644 --- a/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift +++ b/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift @@ -28,13 +28,20 @@ public final class AskKeyAppDelegate: NSObject, UIApplicationDelegate, UNUserNot } } - /// A push for the app in front: fetch at once and show no banner. + /// How a notification shows while the app is in front: the system + /// banner, in Notification Center and with its sound, as when the app is + /// not (decision 8 of #344). + static let foregroundPresentation: UNNotificationPresentationOptions = [.banner, .list, .sound] + + /// A push for the app in front: the system banner shows as usual and the + /// app fetches at once. The request's page does not open by itself; the + /// Requests tab's badge and its highlighted row show the new request. public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo let arrivedAt = notification.date let identifier = notification.request.identifier - completionHandler([]) + completionHandler(Self.foregroundPresentation) Task { @MainActor in await model.receivedPush(userInfo: userInfo, arrivedAt: arrivedAt, notificationIdentifier: identifier) } diff --git a/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings b/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings index 6e73a751..0698c3ff 100644 --- a/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings +++ b/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings @@ -69,6 +69,57 @@ } } }, + "common.openSettings": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open Settings" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "打开“设置”" + } + } + } + }, + "history.empty.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Requests sent to this iPhone are listed here after they end, for 30 days." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "发到这台 iPhone 的请求处理后会记在这里,保留 30 天。" + } + } + } + }, + "history.empty.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No History" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "还没有记录" + } + } + } + }, "list.account.restricted": { "extractionState": "manual", "localizations": { @@ -120,70 +171,155 @@ } } }, - "list.deliveries.polling %@": { + "list.empty.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "After pairing, a Mac sends its agents' requests here when you're away from it." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "配对后,Mac 上 Agent 的请求会在你不在 Mac 前时发到这里。" + } + } + } + }, + "list.empty.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No Paired Macs Yet" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "还没有配对的 Mac" + } + } + } + }, + "list.footer": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "When an agent on one of these Macs wants a credential and you're away, the request comes to this iPhone." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "这些 Mac 上的 Agent 想用凭证、而你不在 Mac 前时,请求会发到这台 iPhone。" + } + } + } + }, + "list.iCloud.restricted": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Restricted" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "受到限制" + } + } + } + }, + "list.iCloud.signedIn": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "%@ · found when Ask Key checked its inbox" + "value": "Signed in" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "%@ · 请旨检查收件箱时发现" + "value": "已登录" } } } }, - "list.deliveries.push %@": { + "list.iCloud.signedOut": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "%@ · arrived through a notification" + "value": "Signed out" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "%@ · 通过通知送达" + "value": "已退出登录" } } } }, - "list.deliveries.title": { + "list.iCloud.unavailable": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Delivery Checks" + "value": "Can't connect" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "送达检查" + "value": "无法连接" } } } }, - "list.empty": { + "list.lastDeliveryCheck": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "No paired Macs yet. On your Mac, open Ask Key's Settings, choose Devices, then Pair a Device." + "value": "Last delivery check" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "还没有配对的 Mac。请在 Mac 上打开请旨的“设置”,选择“设备”,再选择“配对设备”。" + "value": "上次送达检查" + } + } + } + }, + "list.lastDeliveryCheck.none": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "None yet" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "还没有" } } } @@ -205,6 +341,23 @@ } } }, + "list.noValues": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Ask Key keeps no credential value on this iPhone." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "请旨不在这台 iPhone 上保存任何凭证的值。" + } + } + } + }, "list.notApprover": { "extractionState": "manual", "localizations": { @@ -307,36 +460,87 @@ } } }, - "list.pair": { + "list.notifications": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Pair a Mac" + "value": "Notifications" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "配对 Mac" + "value": "通知" + } + } + } + }, + "list.notifications.off": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Notifications are off, so Ask Key can't tell you when a request arrives." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "通知已关闭。请求到达时,请旨无法提醒你。" + } + } + } + }, + "list.notifications.stateOff": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Off" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已关闭" } } } }, - "list.pairedOn %@": { + "list.notifications.stateOn": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Paired %@" + "value": "On" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "配对于 %@" + "value": "已开启" + } + } + } + }, + "list.pair": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pair a Mac" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "配对 Mac" } } } @@ -409,19 +613,87 @@ } } }, - "list.title": { + "list.thisIPhone": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This iPhone" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "这台 iPhone" + } + } + } + }, + "list.version %@": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Paired Macs" + "value": "Version %@" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "已配对的 Mac" + "value": "版本 %@" + } + } + } + }, + "mac.detail.lastReached": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Last reached" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "上次联系" + } + } + } + }, + "mac.detail.paired": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Paired" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "配对于" + } + } + } + }, + "mac.remove.footer": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This iPhone stops approving this Mac's requests at once and drops the pending ones." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "这台 iPhone 会立即停止审批这台 Mac 的请求,并丢弃待处理的请求。" } } } @@ -1378,6 +1650,91 @@ } } }, + "request.empty.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "When an agent on your Mac wants a credential and you're away, the request appears here." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "Mac 上的 Agent 想用凭证、而你不在 Mac 前时,请求会出现在这里。" + } + } + } + }, + "request.empty.reachable %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ Macs can reach this iPhone" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "%@ 台 Mac 可以发来请求" + } + } + } + }, + "request.empty.reachableOne": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "1 Mac can reach this iPhone" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "1 台 Mac 可以发来请求" + } + } + } + }, + "request.empty.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No Requests" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "没有待处理的请求" + } + } + } + }, + "request.empty.unreachable": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Your Macs can't reach this iPhone right now" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "Mac 暂时无法联系这台 iPhone" + } + } + } + }, "request.handsOver.file %@ %@": { "extractionState": "manual", "localizations": { @@ -1446,6 +1803,40 @@ } } }, + "request.list.footnote": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Allowing needs Face ID. Denying doesn't." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "允许要用面容 ID,拒绝不需要。" + } + } + } + }, + "request.list.footnote.touchID": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Allowing needs Touch ID. Denying doesn't." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "允许要用触控 ID,拒绝不需要。" + } + } + } + }, "request.localAgent": { "extractionState": "manual", "localizations": { @@ -1837,19 +2228,36 @@ } } }, - "request.section.title": { + "request.row.sending": { "extractionState": "manual", "localizations": { "en": { "stringUnit": { "state": "translated", - "value": "Requests" + "value": "Sending your decision…" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "请求" + "value": "正在发送你的决定…" + } + } + } + }, + "request.row.waiting": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Sent, waiting for the Mac" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "已发送,等待 Mac 执行" } } } @@ -2245,6 +2653,57 @@ } } }, + "tab.history": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "History" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "记录" + } + } + } + }, + "tab.macs": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Macs" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "Mac" + } + } + } + }, + "tab.requests": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Requests" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "请求" + } + } + } + }, "unusable.confirmTitle": { "extractionState": "manual", "localizations": { diff --git a/iOS/AskKeyiOSKit/Services/AppEnvironment.swift b/iOS/AskKeyiOSKit/Services/AppEnvironment.swift index cab195eb..54f39ee2 100644 --- a/iOS/AskKeyiOSKit/Services/AppEnvironment.swift +++ b/iOS/AskKeyiOSKit/Services/AppEnvironment.swift @@ -37,6 +37,17 @@ public protocol CameraAccessChecking: Sendable { func requestAccess() async -> Bool } +/// Whether Ask Key may show notifications, as Settings → Ask Key → +/// Notifications says. +public enum NotificationAuthorization: Hashable, Sendable { + /// Allowed, including delivered quietly or provisionally. + case allowed + /// The person turned notifications off for Ask Key. + case denied + /// The person was not asked yet. + case notDetermined +} + /// The system notification center as the app uses it. A push is only a /// hint to fetch the inbox: nothing here acts on a notification's text, /// category or action. @@ -45,6 +56,8 @@ public protocol NotificationCenterAccess: Sendable { func requestAuthorizationAndRegister() async /// At a later launch: registers again, and asks only if the person was never asked. func registerAtLaunch() async + /// Reads the current authorization; asks for nothing. + func authorization() async -> NotificationAuthorization /// The pushes for this device's own inbox that are still in Notification Center. func deliveredPushHints(for device: DeviceID) async -> [PushHint] func removeDeliveredNotifications(identifiers: [String]) diff --git a/iOS/AskKeyiOSKit/Services/LiveServices.swift b/iOS/AskKeyiOSKit/Services/LiveServices.swift index f276ad78..d856aea2 100644 --- a/iOS/AskKeyiOSKit/Services/LiveServices.swift +++ b/iOS/AskKeyiOSKit/Services/LiveServices.swift @@ -85,6 +85,14 @@ struct UserNotificationCenterAccess: NotificationCenterAccess { } } + func authorization() async -> NotificationAuthorization { + switch await UNUserNotificationCenter.current().notificationSettings().authorizationStatus { + case .authorized, .provisional, .ephemeral: return .allowed + case .denied: return .denied + default: return .notDetermined + } + } + func deliveredPushHints(for device: DeviceID) async -> [PushHint] { let delivered = await UNUserNotificationCenter.current().deliveredNotifications() return delivered.compactMap { notification in diff --git a/iOS/AskKeyiOSKit/Views/Components.swift b/iOS/AskKeyiOSKit/Views/Components.swift index da7f7fea..78b23301 100644 --- a/iOS/AskKeyiOSKit/Views/Components.swift +++ b/iOS/AskKeyiOSKit/Views/Components.swift @@ -118,3 +118,229 @@ extension View { .background(Color(uiColor: .systemGroupedBackground).ignoresSafeArea()) } } + +extension View { + /// Wraps a tab's content for the app: scrollable on a grouped background + /// and at least as tall as the visible area, so an empty state centers + /// itself in the space below any banner. + func tabScaffold() -> some View { + GeometryReader { proxy in + ScrollView { + self.frame(maxWidth: .infinity, minHeight: proxy.size.height, alignment: .top) + } + } + .background(Color(uiColor: .systemGroupedBackground).ignoresSafeArea()) + } +} + +// MARK: Grouped lists + +/// An inset grouped section in the iOS style, drawn by SwiftUI alone so the +/// screens that use it render for review exactly as the app shows them: an +/// optional header, the rows on one rounded card, and an optional footer. +/// Rows separate themselves with `GroupedDivider`. +struct GroupedSection: View { + var header: Text? + @ViewBuilder var content: Content + @ViewBuilder var footer: Footer + + var body: some View { + VStack(alignment: .leading, spacing: 7) { + if let header { + header + .font(.footnote) + .foregroundStyle(.secondary) + .padding(.horizontal, 16) + .accessibilityAddTraits(.isHeader) + } + VStack(spacing: 0) { content } + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color(uiColor: .secondarySystemGroupedBackground)) + .clipShape(RoundedRectangle(cornerRadius: GroupedMetrics.cornerRadius, style: .continuous)) + footer + .font(.footnote) + .foregroundStyle(.secondary) + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 16) + } + } +} + +extension GroupedSection where Footer == EmptyView { + init(header: Text? = nil, @ViewBuilder content: () -> Content) { + self.init(header: header, content: content) { EmptyView() } + } +} + +enum GroupedMetrics { + static let cornerRadius: CGFloat = 26 + static let rowMinHeight: CGFloat = 52 + /// The leading inset of a row's divider when the row starts with a symbol. + static let symbolInset: CGFloat = 62 +} + +/// The hairline between two rows of a section. +struct GroupedDivider: View { + var leadingInset: CGFloat = 16 + + var body: some View { + Divider().padding(.leading, leadingInset) + } +} + +/// A tappable row: the whole row is the target, and it is shaded while pressed. +struct GroupedRowButtonStyle: ButtonStyle { + func makeBody(configuration: Configuration) -> some View { + configuration.label + .contentShape(Rectangle()) + .background(configuration.isPressed ? Color(uiColor: .systemFill) : Color.clear) + } +} + +/// The disclosure chevron at a navigating row's trailing edge. +struct RowChevron: View { + var body: some View { + Image(systemName: "chevron.right") + .font(.footnote.weight(.semibold)) + .foregroundStyle(.tertiary) + .accessibilityHidden(true) + } +} + +/// A row with a label and a value; the value moves below the label when +/// both do not fit on one line, as with large Dynamic Type sizes. +struct ValueRow: View { + var symbol: String? + var symbolColor: Color = .secondary + @ViewBuilder var label: Title + @ViewBuilder var value: Value + + var body: some View { + HStack(spacing: 14) { + if let symbol { + Image(systemName: symbol) + .font(.body) + .foregroundStyle(symbolColor) + .frame(width: 32) + .accessibilityHidden(true) + } + ViewThatFits(in: .horizontal) { + HStack(spacing: 12) { + label.foregroundStyle(.primary) + Spacer(minLength: 8) + value + } + VStack(alignment: .leading, spacing: 2) { + label.foregroundStyle(.primary) + value + } + .frame(maxWidth: .infinity, alignment: .leading) + } + } + .padding(.horizontal, 16) + .padding(.vertical, 11) + .frame(minHeight: GroupedMetrics.rowMinHeight) + .accessibilityElement(children: .combine) + } +} + +/// A problem that needs Settings, at the top of a tab: an orange symbol, one +/// sentence and **Open Settings**. +struct BannerRow: View { + let symbol: String + let text: Text + let onOpenSettings: () -> Void + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 12) { + Image(systemName: symbol) + .font(.body.weight(.semibold)) + .foregroundStyle(.orange) + .frame(width: 28) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 10) { + text + .font(.body) + .fixedSize(horizontal: false, vertical: true) + Button(action: onOpenSettings) { Text("common.openSettings", bundle: .kit) } + .buttonStyle(.bordered) + .controlSize(.small) + .buttonBorderShape(.capsule) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .padding(16) + .frame(maxWidth: .infinity, alignment: .leading) + .background(RoundedRectangle(cornerRadius: GroupedMetrics.cornerRadius, style: .continuous) + .fill(Color(uiColor: .secondarySystemGroupedBackground))) + .accessibilityElement(children: .contain) + } +} + +/// A tab's empty state: a symbol in a circle, a title, one sentence, and an +/// optional accessory below. +struct EmptyStateView: View { + let symbol: String + let title: LocalizedStringKey + let detail: LocalizedStringKey + @ViewBuilder var accessory: Accessory + @ScaledMetric(relativeTo: .largeTitle) private var circle: CGFloat = 72 + + var body: some View { + VStack(spacing: 10) { + Image(systemName: symbol) + .font(.largeTitle) + .foregroundStyle(.secondary) + .frame(width: circle, height: circle) + .background(Circle().fill(Color(uiColor: .tertiarySystemFill))) + .padding(.bottom, 6) + .accessibilityHidden(true) + Text(title, bundle: .kit) + .font(.title3.bold()) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .accessibilityAddTraits(.isHeader) + Text(detail, bundle: .kit) + .font(.subheadline) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + accessory + .padding(.top, 10) + } + .padding(.horizontal, 24) + .frame(maxWidth: .infinity) + } +} + +extension EmptyStateView where Accessory == EmptyView { + init(symbol: String, title: LocalizedStringKey, detail: LocalizedStringKey) { + self.init(symbol: symbol, title: title, detail: detail) { EmptyView() } + } +} + +/// **Pair a Mac**, the primary action of an empty list. +struct PairButton: View { + let action: () -> Void + + var body: some View { + Button(action: action) { + Label { Text("list.pair", bundle: .kit) } icon: { Image(systemName: "qrcode.viewfinder") } + } + .buttonStyle(.borderedProminent) + .controlSize(.large) + .buttonBorderShape(.capsule) + } +} + +/// A time before `now` in words, such as "2 min. ago", in the screen's language. +enum RelativeTime { + static func text(_ date: Date, now: Date, locale: Locale) -> String { + let formatter = RelativeDateTimeFormatter() + formatter.locale = locale + formatter.unitsStyle = .short + formatter.dateTimeStyle = .named + return formatter.localizedString(for: min(date, now), relativeTo: now) + } +} diff --git a/iOS/AskKeyiOSKit/Views/HistoryView.swift b/iOS/AskKeyiOSKit/Views/HistoryView.swift new file mode 100644 index 00000000..fe283617 --- /dev/null +++ b/iOS/AskKeyiOSKit/Views/HistoryView.swift @@ -0,0 +1,25 @@ +import SwiftUI + +/// The History tab (ADR 0014 → iPhone app, History, amended by #345). Until +/// the app keeps a history (#349), it shows only its empty state. +struct HistoryView: View { + var body: some View { + HistoryContent() + .tabScaffold() + .navigationTitle(Text(HomeTab.history.title, bundle: .kit)) + .navigationBarTitleDisplayMode(.large) + } +} + +/// The History tab's content, drawn by SwiftUI alone so it renders for review. +struct HistoryContent: View { + var body: some View { + VStack(spacing: 0) { + Spacer(minLength: 24) + EmptyStateView(symbol: "clock.arrow.circlepath", title: "history.empty.title", detail: "history.empty.detail") + Spacer(minLength: 24) + } + .padding(.horizontal, 16) + .padding(.bottom, 24) + } +} diff --git a/iOS/AskKeyiOSKit/Views/MacDetailView.swift b/iOS/AskKeyiOSKit/Views/MacDetailView.swift index 02a48829..dd0e126f 100644 --- a/iOS/AskKeyiOSKit/Views/MacDetailView.swift +++ b/iOS/AskKeyiOSKit/Views/MacDetailView.swift @@ -16,9 +16,10 @@ struct MacDetailView: View { private var row: PairedMacRow? { model.pairedMacs.first { $0.id == macID } } var body: some View { - Group { + TimelineView(.periodic(from: .now, by: 30)) { context in if let row { - MacDetailContent(row: row, renameProblem: renameProblem, removalFailed: removalFailed, + MacDetailContent(row: row, now: context.date, renameProblem: renameProblem, + removalFailed: removalFailed, onRename: { newName = row.name renaming = true @@ -72,55 +73,112 @@ enum MacRemovalText { static var confirm: Text { Text("list.remove.confirm", bundle: .kit) } } +/// The Mac's detail as a grouped list: the Mac, whether this iPhone +/// approves its requests (#342's status line), when it was paired and last +/// reached, Rename, and Remove in its own section. struct MacDetailContent: View { let row: PairedMacRow + var now: Date = .now var renameProblem: RenameProblem? var removalFailed = false let onRename: () -> Void let onRemove: () -> Void + @Environment(\.locale) private var locale + @ScaledMetric(relativeTo: .largeTitle) private var circle: CGFloat = 84 var body: some View { - VStack(alignment: .leading, spacing: 20) { - VStack(alignment: .leading, spacing: 8) { - Text(verbatim: row.name) - .font(.largeTitle.bold()) - .fixedSize(horizontal: false, vertical: true) - Text("list.pairedOn \(row.pairedAt, format: .dateTime.year().month().day())", bundle: .kit) - .foregroundStyle(.secondary) - if let reached = row.lastReachedAt { - Text("list.lastReached \(reached, format: .dateTime.year().month().day().hour().minute())", bundle: .kit) - .foregroundStyle(.secondary) - } else { - Text("list.notReached", bundle: .kit) - .foregroundStyle(.orange) + VStack(spacing: 24) { + header + GroupedSection { + ValueRow { + Text("mac.detail.paired", bundle: .kit) + } value: { + Text(row.pairedAt, format: .dateTime.year().month().day()).foregroundStyle(.secondary) + } + GroupedDivider() + ValueRow { + Text("mac.detail.lastReached", bundle: .kit) + } value: { + if let reached = row.lastReachedAt { + Text(verbatim: RelativeTime.text(reached, now: now, locale: locale)).foregroundStyle(.secondary) + } else { + Text("list.notReached", bundle: .kit).foregroundStyle(.orange) + } } - Button(action: onRename) { Text("mac.rename", bundle: .kit).font(.subheadline.weight(.semibold)) } - .buttonStyle(.plain) - .foregroundStyle(Color.accentColor) } - if let renameProblem { - NoticeCard(symbol: "exclamationmark.triangle.fill", tone: .warning, text: Self.text(renameProblem)) + GroupedSection { + Button(action: onRename) { + HStack { + Text("mac.rename", bundle: .kit).foregroundStyle(.primary) + Spacer(minLength: 8) + RowChevron() + } + .padding(.horizontal, 16) + .padding(.vertical, 11) + .frame(minHeight: GroupedMetrics.rowMinHeight) + } + .buttonStyle(GroupedRowButtonStyle()) + } footer: { + if let renameProblem { + Self.text(renameProblem).foregroundStyle(.orange) + } else { + Text("mac.rename.message", bundle: .kit) + } } - // Pairing sets the flag; only a Mac paired before #336 without - // approval lacks it, and only pairing again can set it. A Mac - // whose removal failed is refused here too (`PairedMacRow`). - if row.isApprover { - NoticeCard(symbol: "checkmark.shield.fill", tone: .success, - text: Text("mac.status.approving", bundle: .kit)) - } else { - NoticeCard(symbol: "exclamationmark.shield.fill", tone: .warning, - text: Text("mac.status.notApproving", bundle: .kit)) + GroupedSection { + Button(role: .destructive, action: onRemove) { + Text("list.remove", bundle: .kit) + .foregroundStyle(.red) + .frame(maxWidth: .infinity) + .padding(.horizontal, 16) + .padding(.vertical, 11) + .frame(minHeight: GroupedMetrics.rowMinHeight) + } + .buttonStyle(GroupedRowButtonStyle()) + } footer: { + VStack(alignment: .leading, spacing: 6) { + if removalFailed { + Text("list.notice.removalFailed", bundle: .kit).foregroundStyle(.orange) + } + Text("mac.remove.footer", bundle: .kit) + } } - if removalFailed { - NoticeCard(symbol: "exclamationmark.triangle.fill", tone: .warning, - text: Text("list.notice.removalFailed", bundle: .kit)) + } + .padding(.horizontal, 16) + .padding(.top, 8) + .padding(.bottom, 24) + .frame(maxWidth: .infinity, alignment: .top) + } + + /// The Mac, its name and the status line. Pairing sets the flag; only a + /// Mac paired before #336 without approval lacks it, and only pairing + /// again can set it. A Mac whose removal failed is refused here too + /// (`PairedMacRow`). + private var header: some View { + VStack(spacing: 10) { + Image(systemName: "laptopcomputer") + .font(.largeTitle) + .foregroundStyle(.secondary) + .frame(width: circle, height: circle) + .background(Circle().fill(Color(uiColor: .secondarySystemGroupedBackground))) + .accessibilityHidden(true) + Text(verbatim: row.name) + .font(.title.bold()) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .accessibilityAddTraits(.isHeader) + HStack(alignment: .firstTextBaseline, spacing: 6) { + Image(systemName: row.isApprover ? "checkmark.shield.fill" : "exclamationmark.shield.fill") + .foregroundStyle(row.isApprover ? Color.green : Color.orange) + .accessibilityHidden(true) + Text(row.isApprover ? "mac.status.approving" : "mac.status.notApproving", bundle: .kit) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) } - Button(action: onRemove) { Text("list.remove", bundle: .kit) } - .buttonStyle(ActionButtonStyle(kind: .destructive)) + .font(.subheadline) + .padding(.horizontal, 8) } - .padding(.horizontal, 20) - .padding(.vertical, 24) - .frame(maxWidth: .infinity, alignment: .leading) + .frame(maxWidth: .infinity) } static func text(_ problem: RenameProblem) -> Text { diff --git a/iOS/AskKeyiOSKit/Views/MacsView.swift b/iOS/AskKeyiOSKit/Views/MacsView.swift new file mode 100644 index 00000000..a06542bb --- /dev/null +++ b/iOS/AskKeyiOSKit/Views/MacsView.swift @@ -0,0 +1,242 @@ +import SwiftUI + +/// The Macs tab (ADR 0014 → iPhone app, Home, amended by #345): the outcome +/// of the last removal, the paired Macs, and this iPhone's own status. +/// **+** starts pairing; a Mac's row opens its detail. +struct MacsView: View { + @Bindable var model: AppModel + @State private var selectedMac: String? + + var body: some View { + TimelineView(.periodic(from: .now, by: 30)) { context in + MacsContent(rows: model.pairedMacs, listNotice: model.listNotice, accountNotice: model.accountNotice, + notificationsOff: model.notificationsOff, lastDeliveryCheck: model.lastDeliveryCheck, + version: AppVersion.current, now: context.date, onPair: model.startPairing, + onSelect: { selectedMac = $0.id }, onDismissNotice: { model.listNotice = nil }) + } + .tabScaffold() + .refreshable { await model.processInbox() } + .navigationTitle(Text(HomeTab.macs.title, bundle: .kit)) + .navigationBarTitleDisplayMode(.large) + .toolbar { + ToolbarItem(placement: .topBarTrailing) { + Button(action: model.startPairing) { + Label { Text("list.pair", bundle: .kit) } icon: { Image(systemName: "plus") } + } + } + } + .navigationDestination(item: $selectedMac) { id in + MacDetailView(model: model, macID: id) + } + .onChange(of: model.openedRequest) { _, opened in + // A tapped notification's page opens over the home; the Mac's + // detail, with its dialogs, closes first. + if opened != nil { selectedMac = nil } + } + } +} + +/// The app's version and build, such as "1.0 (12)". +enum AppVersion { + static var current: String { + let info = Bundle.main.infoDictionary + let version = info?["CFBundleShortVersionString"] as? String ?? "?" + let build = info?["CFBundleVersion"] as? String ?? "?" + return "\(version) (\(build))" + } +} + +/// The Macs tab's content, drawn by SwiftUI alone so it renders for review +/// as the app shows it: the removal notice, one list of Macs with the rule +/// in its footer (or the empty state), then This iPhone. +struct MacsContent: View { + let rows: [PairedMacRow] + let listNotice: ListNotice? + let accountNotice: AccountNotice? + let notificationsOff: Bool + let lastDeliveryCheck: Date? + let version: String + let now: Date + let onPair: () -> Void + let onSelect: (PairedMacRow) -> Void + let onDismissNotice: () -> Void + + var body: some View { + VStack(spacing: 24) { + if let listNotice { + RemovalNoticeRow(notice: listNotice, onDismiss: onDismissNotice) + } + if rows.isEmpty { + EmptyStateView(symbol: "laptopcomputer", title: "list.empty.title", detail: "list.empty.detail") { + PairButton(action: onPair) + } + .padding(.vertical, 12) + } else { + GroupedSection { + ForEach(Array(rows.enumerated()), id: \.element.id) { index, row in + if index > 0 { GroupedDivider(leadingInset: GroupedMetrics.symbolInset) } + MacRow(row: row, now: now) { onSelect(row) } + } + } footer: { + Text("list.footer", bundle: .kit) + } + } + ThisIPhoneSection(accountNotice: accountNotice, notificationsOff: notificationsOff, + lastDeliveryCheck: lastDeliveryCheck, version: version) + } + .padding(.horizontal, 16) + .padding(.top, 8) + .padding(.bottom, 24) + } +} + +/// A Mac's row: its name, when this iPhone last heard from it, and only for +/// the exception, an entry without the approval flag, that this iPhone +/// cannot approve its requests. Tapping it opens the Mac's detail. +private struct MacRow: View { + let row: PairedMacRow + let now: Date + let onSelect: () -> Void + @Environment(\.locale) private var locale + + var body: some View { + Button(action: onSelect) { + HStack(spacing: 14) { + Image(systemName: "laptopcomputer") + .font(.title3) + .foregroundStyle(.secondary) + .frame(width: 32) + .accessibilityHidden(true) + VStack(alignment: .leading, spacing: 3) { + Text(verbatim: row.name) + .font(.body) + .foregroundStyle(.primary) + .multilineTextAlignment(.leading) + if let reached = row.lastReachedAt { + Text("list.lastReached \(RelativeTime.text(reached, now: now, locale: locale))", bundle: .kit) + .foregroundStyle(.secondary) + } else { + Text("list.notReached", bundle: .kit) + .foregroundStyle(.orange) + } + if !row.isApprover { + Label { Text("list.notApprover", bundle: .kit) } icon: { + Image(systemName: "exclamationmark.shield.fill") + } + .foregroundStyle(.orange) + .multilineTextAlignment(.leading) + } + } + .font(.subheadline) + .frame(maxWidth: .infinity, alignment: .leading) + RowChevron() + } + .padding(.horizontal, 16) + .padding(.vertical, 11) + .frame(minHeight: GroupedMetrics.rowMinHeight) + } + .buttonStyle(GroupedRowButtonStyle()) + } +} + +/// The outcome of the last removal, at the top of the tab until dismissed. +struct RemovalNoticeRow: View { + let notice: ListNotice + let onDismiss: () -> Void + + var body: some View { + HStack(alignment: .top, spacing: 12) { + Image(systemName: symbol.name) + .font(.title3) + .foregroundStyle(symbol.color) + .frame(width: 28) + .accessibilityHidden(true) + Self.text(notice) + .font(.body) + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + Button(action: onDismiss) { + Image(systemName: "xmark.circle.fill") + .font(.title3) + .foregroundStyle(.secondary) + } + .buttonStyle(.plain) + .accessibilityLabel(Text("common.dismiss", bundle: .kit)) + } + .padding(16) + .background(RoundedRectangle(cornerRadius: GroupedMetrics.cornerRadius, style: .continuous) + .fill(Color(uiColor: .secondarySystemGroupedBackground))) + .accessibilityElement(children: .contain) + } + + private var symbol: (name: String, color: Color) { + switch notice { + case .removed(_, true): return ("checkmark.circle.fill", .green) + case .removed(_, false), .removalFailed: return ("exclamationmark.triangle.fill", .orange) + case .removedByMac: return ("info.circle.fill", .accentColor) + } + } + + static func text(_ notice: ListNotice) -> Text { + switch notice { + case .removed(let name, true): return Text("list.notice.removedAndTold \(name)", bundle: .kit) + case .removed(let name, false): return Text("list.notice.removedNotTold \(name)", bundle: .kit) + case .removedByMac(let name): return Text("list.notice.removedByMac \(name)", bundle: .kit) + case .removalFailed: return Text("list.notice.removalFailed", bundle: .kit) + } + } +} + +/// This iPhone: whether iCloud and notifications work, the last delivery +/// check, and that no credential value is kept here, with the version. +private struct ThisIPhoneSection: View { + let accountNotice: AccountNotice? + let notificationsOff: Bool + let lastDeliveryCheck: Date? + let version: String + + var body: some View { + GroupedSection(header: Text("list.thisIPhone", bundle: .kit)) { + ValueRow(symbol: accountNotice == nil ? "icloud" : "icloud.slash") { + Text(verbatim: "iCloud") + } value: { + iCloudValue + } + GroupedDivider(leadingInset: GroupedMetrics.symbolInset) + ValueRow(symbol: notificationsOff ? "bell.slash" : "bell") { + Text("list.notifications", bundle: .kit) + } value: { + if notificationsOff { + Text("list.notifications.stateOff", bundle: .kit).foregroundStyle(.orange) + } else { + Text("list.notifications.stateOn", bundle: .kit).foregroundStyle(.secondary) + } + } + GroupedDivider(leadingInset: GroupedMetrics.symbolInset) + ValueRow(symbol: "checkmark.circle") { + Text("list.lastDeliveryCheck", bundle: .kit) + } value: { + if let lastDeliveryCheck { + Text(lastDeliveryCheck, format: .dateTime.month(.abbreviated).day().hour().minute()) + .foregroundStyle(.secondary) + } else { + Text("list.lastDeliveryCheck.none", bundle: .kit).foregroundStyle(.secondary) + } + } + } footer: { + VStack(alignment: .leading, spacing: 2) { + Text("list.noValues", bundle: .kit) + Text("list.version \(version)", bundle: .kit) + } + } + } + + @ViewBuilder private var iCloudValue: some View { + switch accountNotice { + case nil: Text("list.iCloud.signedIn", bundle: .kit).foregroundStyle(.secondary) + case .signedOut: Text("list.iCloud.signedOut", bundle: .kit).foregroundStyle(.orange) + case .restricted: Text("list.iCloud.restricted", bundle: .kit).foregroundStyle(.orange) + case .unavailable: Text("list.iCloud.unavailable", bundle: .kit).foregroundStyle(.orange) + } + } +} diff --git a/iOS/AskKeyiOSKit/Views/PairedMacsView.swift b/iOS/AskKeyiOSKit/Views/PairedMacsView.swift deleted file mode 100644 index 8a03645c..00000000 --- a/iOS/AskKeyiOSKit/Views/PairedMacsView.swift +++ /dev/null @@ -1,208 +0,0 @@ -import SwiftUI - -/// The home screen: pending requests when there are any, then the paired -/// Macs and pairing as before. -struct PairedMacsView: View { - @Bindable var model: AppModel - @State private var selectedMac: String? - @State private var promptedName = "" - - var body: some View { - PairedMacsContent(rows: model.pairedMacs, accountNotice: model.accountNotice, listNotice: model.listNotice, - records: model.deliveryRecords, hasRequests: !model.requests.isEmpty, - onPair: model.startPairing, onSelect: { selectedMac = $0.id }, - onDismissNotice: { model.listNotice = nil }) { - RequestList(model: model) - } - .screenScaffold() - .refreshable { await model.processInbox() } - .toolbar(.hidden, for: .navigationBar) - .navigationDestination(item: $selectedMac) { id in - MacDetailView(model: model, macID: id) - } - .sheet(item: $model.openedRequest) { opened in - OpenedRequestView(model: model, id: opened.id) { model.openedRequest = nil } - .privacyCover(isAuthenticating: model.isAuthenticating) - } - .alert(Text("mac.renamedDuplicate.title", bundle: .kit), isPresented: renamePromptShown, - presenting: model.renamePrompt) { prompt in - TextField(text: $promptedName) { Text("mac.rename.placeholder", bundle: .kit) } - Button { - let name = promptedName - Task { _ = await model.renameMac(id: prompt.macID, to: name) } - } label: { - Text("mac.rename.save", bundle: .kit) - } - Button(role: .cancel) { model.renamePrompt = nil } label: { Text("mac.renamedDuplicate.later", bundle: .kit) } - } message: { prompt in - Text("mac.renamedDuplicate.message \(Text(verbatim: prompt.takenName)) \(Text(verbatim: prompt.newName))", - bundle: .kit) - } - .onChange(of: model.renamePrompt) { _, prompt in - if let prompt { promptedName = prompt.newName } - } - .onChange(of: model.openedRequest) { _, opened in - if opened != nil { selectedMac = nil } - } - } - - /// The rename prompt waits until the pairing sheet has closed. - private var renamePromptShown: Binding { - Binding(get: { model.renamePrompt != nil && model.pairing == nil }, - set: { if !$0 { model.renamePrompt = nil } }) - } -} - -/// The requests, then the paired Macs: name, paired date, last reached and, -/// for a Mac paired before #336 without approval, that this iPhone can't -/// approve its requests; the iCloud state and the outcome of the last -/// removal; and the delivery checks this iPhone answered. -struct PairedMacsContent: View { - let rows: [PairedMacRow] - let accountNotice: AccountNotice? - let listNotice: ListNotice? - let records: [DeliveryRecord] - var hasRequests = false - let onPair: () -> Void - let onSelect: (PairedMacRow) -> Void - let onDismissNotice: () -> Void - @ViewBuilder var requests: Requests - - var body: some View { - ScreenContent(title: hasRequests ? "request.section.title" : "list.title") { - if let accountNotice { - NoticeCard(symbol: "icloud.slash", tone: .warning, text: Text(Self.explanation(accountNotice), bundle: .kit)) - } - if hasRequests { - requests - Text("list.title", bundle: .kit) - .font(.title2.bold()) - .padding(.top, 8) - } - if let listNotice { - HStack(alignment: .top) { - NoticeCard(symbol: "info.circle.fill", tone: listNotice == .removalFailed ? .warning : .info, - text: Self.text(listNotice)) - Button(action: onDismissNotice) { - Image(systemName: "xmark.circle.fill").font(.title3).foregroundStyle(.secondary) - } - .accessibilityLabel(Text("common.dismiss", bundle: .kit)) - } - } - if rows.isEmpty { - NoticeCard(symbol: "desktopcomputer", text: Text("list.empty", bundle: .kit)) - } else { - VStack(spacing: 12) { - ForEach(rows) { row in - MacRow(row: row) { onSelect(row) } - } - } - } - Button(action: onPair) { - Label { Text("list.pair", bundle: .kit) } icon: { Image(systemName: "qrcode.viewfinder") } - } - .buttonStyle(ActionButtonStyle()) - if !records.isEmpty { - VStack(alignment: .leading, spacing: 8) { - Text("list.deliveries.title", bundle: .kit) - .font(.headline) - ForEach(Array(records.suffix(5).reversed()), id: \.self) { record in - Self.recordText(record) - .font(.footnote) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - } - } - } - } - - static func explanation(_ notice: AccountNotice) -> LocalizedStringKey { - switch notice { - case .signedOut: return "list.account.signedOut" - case .restricted: return "list.account.restricted" - case .unavailable: return "list.account.unavailable" - } - } - - static func text(_ notice: ListNotice) -> Text { - switch notice { - case .removed(let name, true): return Text("list.notice.removedAndTold \(name)", bundle: .kit) - case .removed(let name, false): return Text("list.notice.removedNotTold \(name)", bundle: .kit) - case .removedByMac(let name): return Text("list.notice.removedByMac \(name)", bundle: .kit) - case .removalFailed: return Text("list.notice.removalFailed", bundle: .kit) - } - } - - static func recordText(_ record: DeliveryRecord) -> Text { - let format = Date.FormatStyle.dateTime.month(.abbreviated).day().hour().minute().second() - switch record.source { - case .push: return Text("list.deliveries.push \(record.arrivedAt, format: format)", bundle: .kit) - case .polling: return Text("list.deliveries.polling \(record.arrivedAt, format: format)", bundle: .kit) - } - } -} - -extension PairedMacsContent where Requests == EmptyView { - init(rows: [PairedMacRow], accountNotice: AccountNotice?, listNotice: ListNotice?, records: [DeliveryRecord], - onPair: @escaping () -> Void, onSelect: @escaping (PairedMacRow) -> Void, - onDismissNotice: @escaping () -> Void) { - self.init(rows: rows, accountNotice: accountNotice, listNotice: listNotice, records: records, hasRequests: false, - onPair: onPair, onSelect: onSelect, onDismissNotice: onDismissNotice) { EmptyView() } - } -} - -/// A Mac's row; tapping it opens the Mac's detail. Pairing makes this iPhone -/// approve a Mac's requests, so only the exception is marked: an entry -/// without the flag. -private struct MacRow: View { - let row: PairedMacRow - let onSelect: () -> Void - - var body: some View { - Button(action: onSelect) { - HStack(alignment: .center, spacing: 14) { - Image(systemName: "laptopcomputer") - .font(.title2) - .foregroundStyle(Color.accentColor) - .frame(width: 32) - VStack(alignment: .leading, spacing: 4) { - Text(verbatim: row.name) - .font(.headline) - .foregroundStyle(.primary) - .multilineTextAlignment(.leading) - Text("list.pairedOn \(row.pairedAt, format: .dateTime.year().month().day())", bundle: .kit) - .font(.footnote) - .foregroundStyle(.secondary) - if let reached = row.lastReachedAt { - Text("list.lastReached \(reached, format: .dateTime.year().month().day().hour().minute())", - bundle: .kit) - .font(.footnote) - .foregroundStyle(.secondary) - } else { - Text("list.notReached", bundle: .kit) - .font(.footnote) - .foregroundStyle(.orange) - } - if !row.isApprover { - Label { Text("list.notApprover", bundle: .kit) } icon: { - Image(systemName: "exclamationmark.shield.fill") - } - .font(.footnote.weight(.semibold)) - .foregroundStyle(.orange) - .multilineTextAlignment(.leading) - } - } - Spacer(minLength: 8) - Image(systemName: "chevron.right") - .font(.footnote.weight(.semibold)) - .foregroundStyle(.tertiary) - } - .padding(14) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .background(RoundedRectangle(cornerRadius: 16, style: .continuous) - .fill(Color(uiColor: .secondarySystemGroupedBackground))) - } -} diff --git a/iOS/AskKeyiOSKit/Views/RequestCardView.swift b/iOS/AskKeyiOSKit/Views/RequestCardView.swift index 3a37958a..e68d6226 100644 --- a/iOS/AskKeyiOSKit/Views/RequestCardView.swift +++ b/iOS/AskKeyiOSKit/Views/RequestCardView.swift @@ -308,21 +308,6 @@ enum RequestCopy { } } -/// The cards, with the model's actions; the countdown redraws every second. -struct RequestList: View { - let model: AppModel - - var body: some View { - TimelineView(.periodic(from: .now, by: 1)) { context in - VStack(spacing: 14) { - ForEach(model.requests) { card in - RequestCardView(model: model, card: card, now: context.date) - } - } - } - } -} - struct RequestCardView: View { let model: AppModel let card: RequestCard diff --git a/iOS/AskKeyiOSKit/Views/RequestsView.swift b/iOS/AskKeyiOSKit/Views/RequestsView.swift new file mode 100644 index 00000000..d6c2f51a --- /dev/null +++ b/iOS/AskKeyiOSKit/Views/RequestsView.swift @@ -0,0 +1,230 @@ +import AskKeyDevices +import SwiftUI +import UIKit + +/// The Requests tab (ADR 0014 → iPhone app, Home, amended by #345): banners +/// for iCloud and notification problems, then the requests that can still +/// be decided or wait for the Mac, or an empty state. Tapping a row opens +/// the request's page. A request that arrives never opens its page by +/// itself; its row is briefly highlighted instead (decision 8 of #344). +struct RequestsView: View { + @Bindable var model: AppModel + @Environment(\.openURL) private var openURL + /// The request IDs as last seen; nil before the first look, so the rows + /// already there when the tab appears are not highlighted. + @State private var seenRequests: Set? + @State private var highlighted: Set = [] + + var body: some View { + TimelineView(.periodic(from: .now, by: 1)) { context in + RequestsContent(cards: model.activeRequests(at: context.date), now: context.date, + hasMacs: !model.pairedMacs.isEmpty, approvingMacs: model.approvingMacCount, + accountNotice: model.accountNotice, notificationsOff: model.notificationsOff, + biometry: model.biometryKind, highlighted: highlighted, + onOpen: { model.open($0.id) }, onPair: model.startPairing, onOpenSettings: openSettings) + } + .tabScaffold() + .refreshable { await model.processInbox() } + .navigationTitle(Text(HomeTab.requests.title, bundle: .kit)) + .navigationBarTitleDisplayMode(.large) + .onChange(of: model.requests.map(\.id), initial: true) { _, ids in + highlightArrivals(ids) + } + } + + private func highlightArrivals(_ ids: [String]) { + let current = Set(ids) + let previous = seenRequests + seenRequests = current + guard let previous else { return } + let arrived = current.subtracting(previous) + guard !arrived.isEmpty else { return } + highlighted.formUnion(arrived) + Task { @MainActor in + try? await Task.sleep(for: .seconds(2)) + withAnimation(.easeOut(duration: 0.8)) { highlighted.subtract(arrived) } + } + } + + private func openSettings(_ page: SettingsPage) { + let address = page == .notifications + ? UIApplication.openNotificationSettingsURLString : UIApplication.openSettingsURLString + if let url = URL(string: address) { openURL(url) } + } +} + +/// Which page of Settings a banner opens: Ask Key's own, or its notifications. +enum SettingsPage: Hashable { + case app + case notifications +} + +/// The Requests tab's content, drawn by SwiftUI alone so it renders for +/// review as the app shows it. A row shows only the card's sentence and the +/// time left, or that a decision was sent; never the command, the folder, +/// the delivered names or the purpose, which only the request's page shows. +struct RequestsContent: View { + let cards: [RequestCard] + let now: Date + let hasMacs: Bool + /// The Macs whose requests this iPhone accepts. + let approvingMacs: Int + let accountNotice: AccountNotice? + let notificationsOff: Bool + var biometry: BiometryKind = .faceID + var highlighted: Set = [] + let onOpen: (RequestCard) -> Void + let onPair: () -> Void + let onOpenSettings: (SettingsPage) -> Void + + var body: some View { + VStack(spacing: 16) { + if let accountNotice { + BannerRow(symbol: Self.symbol(accountNotice), text: Text(Self.explanation(accountNotice), bundle: .kit)) { + onOpenSettings(.app) + } + } + if notificationsOff { + BannerRow(symbol: "bell.slash", text: Text("list.notifications.off", bundle: .kit)) { + onOpenSettings(.notifications) + } + } + if cards.isEmpty { + Spacer(minLength: 24) + if hasMacs { + EmptyStateView(symbol: "tray", title: "request.empty.title", detail: "request.empty.detail") { + ReachabilityCapsule(approvingMacs: approvingMacs, + cannotReach: Self.macsCannotReach(accountNotice: accountNotice, + notificationsOff: notificationsOff)) + } + } else { + EmptyStateView(symbol: "laptopcomputer", title: "list.empty.title", detail: "list.empty.detail") { + PairButton(action: onPair) + } + } + Spacer(minLength: 24) + } else { + GroupedSection { + ForEach(Array(cards.enumerated()), id: \.element.id) { index, card in + if index > 0 { GroupedDivider() } + RequestRow(card: card, now: now, isHighlighted: highlighted.contains(card.id)) { onOpen(card) } + } + } footer: { + Text(biometry == .touchID ? "request.list.footnote.touchID" : "request.list.footnote", bundle: .kit) + } + } + } + .padding(.horizontal, 16) + .padding(.top, 8) + .padding(.bottom, 24) + } + + /// While a banner shows, the Macs cannot reach this iPhone, or cannot + /// get the person's attention, so the empty state says so. + static func macsCannotReach(accountNotice: AccountNotice?, notificationsOff: Bool) -> Bool { + accountNotice != nil || notificationsOff + } + + static func explanation(_ notice: AccountNotice) -> LocalizedStringKey { + switch notice { + case .signedOut: return "list.account.signedOut" + case .restricted: return "list.account.restricted" + case .unavailable: return "list.account.unavailable" + } + } + + static func symbol(_ notice: AccountNotice) -> String { + switch notice { + case .signedOut, .restricted: return "icloud.slash" + case .unavailable: return "exclamationmark.icloud" + } + } +} + +/// One request: its sentence, names bold, in at most two lines (more at +/// accessibility text sizes), and the time left, orange under a minute, or +/// that the decision was sent. +struct RequestRow: View { + let card: RequestCard + let now: Date + var isHighlighted = false + let onOpen: () -> Void + @Environment(\.dynamicTypeSize) private var typeSize + + var body: some View { + Button(action: onOpen) { + HStack(spacing: 12) { + VStack(alignment: .leading, spacing: 6) { + RequestSentence(card: card) + .font(.body) + .foregroundStyle(.primary) + .multilineTextAlignment(.leading) + .lineLimit(typeSize.isAccessibilitySize ? 5 : 2) + status + .font(.subheadline) + } + .frame(maxWidth: .infinity, alignment: .leading) + RowChevron() + } + .padding(.horizontal, 16) + .padding(.vertical, 12) + .frame(minHeight: GroupedMetrics.rowMinHeight) + .background(isHighlighted ? Color.accentColor.opacity(0.14) : Color.clear) + } + .buttonStyle(GroupedRowButtonStyle()) + } + + @ViewBuilder private var status: some View { + switch card.phase(at: now) { + case .sending: + Label { Text("request.row.sending", bundle: .kit) } icon: { Image(systemName: "arrow.up.circle") } + .foregroundStyle(.secondary) + case .waiting: + Label { Text("request.row.waiting", bundle: .kit) } icon: { Image(systemName: "hourglass") } + .foregroundStyle(.secondary) + default: + let seconds = card.secondsLeft(at: now) + Label { Text("request.timeLeft.value \(Self.clock(seconds))", bundle: .kit) } icon: { + Image(systemName: "clock") + } + .monospacedDigit() + .foregroundStyle(seconds < 60 ? Color.orange : Color.secondary) + } + } + + /// Seconds as minutes and seconds, such as "4:32". + static func clock(_ seconds: Int) -> String { + String(format: "%d:%02d", seconds / 60, seconds % 60) + } +} + +/// Under the empty state: a green dot and how many Macs can send requests +/// here, or an orange dot while a banner says why they cannot. +struct ReachabilityCapsule: View { + let approvingMacs: Int + let cannotReach: Bool + + var body: some View { + HStack(spacing: 8) { + Circle() + .fill(cannotReach || approvingMacs == 0 ? Color.orange : Color.green) + .frame(width: 8, height: 8) + .accessibilityHidden(true) + text + .font(.subheadline) + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + } + .padding(.horizontal, 14) + .padding(.vertical, 8) + .background(Capsule().fill(Color(uiColor: .secondarySystemGroupedBackground))) + .accessibilityElement(children: .combine) + } + + private var text: Text { + if cannotReach { return Text("request.empty.unreachable", bundle: .kit) } + if approvingMacs == 1 { return Text("request.empty.reachableOne", bundle: .kit) } + return Text("request.empty.reachable \(String(approvingMacs))", bundle: .kit) + } +} diff --git a/iOS/AskKeyiOSKit/Views/RootView.swift b/iOS/AskKeyiOSKit/Views/RootView.swift index 209b9179..1803250f 100644 --- a/iOS/AskKeyiOSKit/Views/RootView.swift +++ b/iOS/AskKeyiOSKit/Views/RootView.swift @@ -17,9 +17,7 @@ public struct AskKeyRootView: View { case .welcome: WelcomeView(model: model) case .ready: - NavigationStack { - PairedMacsView(model: model) - } + HomeTabs(model: model) case .unusableIdentity: UnusableIdentityView(model: model) } @@ -36,7 +34,7 @@ public struct AskKeyRootView: View { await model.runForegroundPolling() } .onChange(of: scenePhase) { _, phase in - if phase == .active { Task { await model.becameActive() } } + if phase == .active { Task { await model.sceneBecameActive() } } } .onChange(of: model.stage) { _, stage in if stage == .ready { Task { await model.becameActive() } } @@ -44,6 +42,85 @@ public struct AskKeyRootView: View { } } +/// The home: Requests, History and Macs, each with its own navigation and +/// large title (ADR 0014 → iPhone app, Home, amended by #345). The Requests +/// tab's badge counts the requests that can still be decided. A request's +/// page opens as a sheet over every tab, from a row or a tapped +/// notification, never by itself when a request arrives. +struct HomeTabs: View { + @Bindable var model: AppModel + @State private var promptedName = "" + + var body: some View { + // Redrawn when a request's countdown ends, so the badge drops it. + TimelineView(.explicit(model.decidableCountChanges)) { context in + TabView(selection: $model.selectedTab) { + NavigationStack { RequestsView(model: model) } + .tabItem { HomeTab.requests.label } + .tag(HomeTab.requests) + .badge(model.decidableRequestCount(at: max(context.date, Date()))) + NavigationStack { HistoryView() } + .tabItem { HomeTab.history.label } + .tag(HomeTab.history) + NavigationStack { MacsView(model: model) } + .tabItem { HomeTab.macs.label } + .tag(HomeTab.macs) + } + } + .sheet(item: $model.openedRequest) { opened in + OpenedRequestView(model: model, id: opened.id) { model.openedRequest = nil } + .privacyCover(isAuthenticating: model.isAuthenticating) + } + .alert(Text("mac.renamedDuplicate.title", bundle: .kit), isPresented: renamePromptShown, + presenting: model.renamePrompt) { prompt in + TextField(text: $promptedName) { Text("mac.rename.placeholder", bundle: .kit) } + Button { + let name = promptedName + Task { _ = await model.renameMac(id: prompt.macID, to: name) } + } label: { + Text("mac.rename.save", bundle: .kit) + } + Button(role: .cancel) { model.renamePrompt = nil } label: { Text("mac.renamedDuplicate.later", bundle: .kit) } + } message: { prompt in + Text("mac.renamedDuplicate.message \(Text(verbatim: prompt.takenName)) \(Text(verbatim: prompt.newName))", + bundle: .kit) + } + .onChange(of: model.renamePrompt) { _, prompt in + if let prompt { promptedName = prompt.newName } + } + } + + /// The rename prompt waits until the pairing sheet has closed. + private var renamePromptShown: Binding { + Binding(get: { model.renamePrompt != nil && model.pairing == nil }, + set: { if !$0 { model.renamePrompt = nil } }) + } +} + +extension HomeTab { + /// The tab's name, also its navigation title. + var title: LocalizedStringKey { + switch self { + case .requests: return "tab.requests" + case .history: return "tab.history" + case .macs: return "tab.macs" + } + } + + /// The tab's symbol; the tab bar fills it where a filled form exists. + var symbol: String { + switch self { + case .requests: return "tray" + case .history: return "clock.arrow.circlepath" + case .macs: return "laptopcomputer" + } + } + + var label: some View { + Label { Text(title, bundle: .kit) } icon: { Image(systemName: symbol) } + } +} + struct UnusableIdentityView: View { let model: AppModel @State private var confirming = false diff --git a/iOS/AskKeyiOSKitTests/Fakes/FakeSystem.swift b/iOS/AskKeyiOSKitTests/Fakes/FakeSystem.swift index d0efcbc3..e84faabf 100644 --- a/iOS/AskKeyiOSKitTests/Fakes/FakeSystem.swift +++ b/iOS/AskKeyiOSKitTests/Fakes/FakeSystem.swift @@ -75,10 +75,21 @@ final class FakeNotifications: NotificationCenterAccess, @unchecked Sendable { private var hints: [PushHint] = [] private var removed: [String] = [] private var requests = 0 + private var current: NotificationAuthorization = .allowed var authorizationRequests: Int { lock.withLock { requests } } var removedIdentifiers: [String] { lock.withLock { removed } } + /// What Settings → Ask Key → Notifications says. + var authorizationState: NotificationAuthorization { + get { lock.withLock { current } } + set { lock.withLock { current = newValue } } + } + + func authorization() async -> NotificationAuthorization { + authorizationState + } + /// The pushes Notification Center holds for this device. var delivered: [PushHint] { get { lock.withLock { hints } } diff --git a/iOS/AskKeyiOSKitTests/HomeTests.swift b/iOS/AskKeyiOSKitTests/HomeTests.swift new file mode 100644 index 00000000..88fe2e50 --- /dev/null +++ b/iOS/AskKeyiOSKitTests/HomeTests.swift @@ -0,0 +1,153 @@ +import AskKeyDevices +import XCTest +@testable import AskKeyiOSKit + +/// The home's tabs (#346): which requests the Requests tab lists and its +/// badge counts, a request arriving in front, the notification +/// authorization behind the banner, and this iPhone's status. +@MainActor +final class HomeTests: XCTestCase { + private var world: TestWorld! + + override func setUp() async throws { + world = TestWorld() + await world.setUpPhone() + try await world.pair() + } + + override func tearDown() async throws { + world = nil + } + + private var now: Date { world.clock.now() } + + private func recordName(_ sealed: SealedApprovalRequest) -> String { + sealed.sealed.messageID.text + } + + // MARK: Requests and the badge + + /// Decision 7 of #344: a request the Mac closed or whose countdown ended + /// leaves the tab; one whose decision was sent stays until the Mac + /// closes it. The badge counts only those that can still be decided. + func testTheRequestsTabListsOnlyRequestsThatCanStillBeDecidedOrWaitForTheMac() async throws { + let decidedOnMac = try await world.sendRequest() + let denied = try await world.sendRequest() + let pending = try await world.sendRequest(lifetime: 120) + await world.model.processInbox() + XCTAssertEqual(Set(world.model.activeRequests(at: now).map(\.id)), + Set([decidedOnMac, denied, pending].map(recordName))) + XCTAssertEqual(world.model.decidableRequestCount(at: now), 3) + + try await world.sendClosed(.decidedOnMac, for: decidedOnMac) + await world.model.decide(.deny, requestID: recordName(denied)) + await world.model.processInbox() + XCTAssertEqual(world.model.activeRequests(at: now).map(\.id), [recordName(pending), recordName(denied)], + "by time left; the sent decision waits for the Mac") + XCTAssertEqual(world.model.decidableRequestCount(at: now), 1) + XCTAssertEqual(world.model.requests.count, 3, "a finished request's page can still show it") + + world.clock.advance(by: 130) + XCTAssertEqual(world.model.activeRequests(at: now).map(\.id), [recordName(denied)]) + XCTAssertEqual(world.model.decidableRequestCount(at: now), 0) + + try await world.sendClosed(.applied, code: .deny, for: denied) + await world.model.processInbox() + XCTAssertTrue(world.model.activeRequests(at: now).isEmpty) + } + + /// The badge changes when a countdown ends, so the home redraws then. + func testTheBadgeIsRedrawnWhenAnUndecidedCountdownEnds() async throws { + try await world.sendRequest(lifetime: 120) + let decided = try await world.sendRequest() + await world.model.processInbox() + await world.model.decide(.deny, requestID: recordName(decided)) + let pending = try XCTUnwrap(world.model.requests.first { $0.decision == nil }) + XCTAssertEqual(world.model.decidableCountChanges, [pending.countdownEnd]) + } + + /// Decision 8 of #344: in front, the notification shows as a banner, the + /// badge counts the request, and neither its page nor the tab changes. + func testARequestArrivingInFrontNeverOpensItsPage() async throws { + XCTAssertEqual(AskKeyAppDelegate.foregroundPresentation, [.banner, .list, .sound]) + world.model.selectedTab = .macs + let sealed = try await world.sendRequest() + await world.model.receivedPush(userInfo: TestWorld.alertPush(for: try world.phone.deviceID, + record: recordName(sealed)), + arrivedAt: now, notificationIdentifier: "arrived") + XCTAssertEqual(world.model.activeRequests(at: now).map(\.id), [recordName(sealed)]) + XCTAssertEqual(world.model.decidableRequestCount(at: now), 1) + XCTAssertNil(world.model.openedRequest) + XCTAssertNil(world.model.opening) + XCTAssertEqual(world.model.selectedTab, .macs) + } + + /// Tapping a row opens that request's page with its card at once. + func testOpeningARowShowsItsCard() async throws { + let sealed = try await world.sendRequest() + await world.model.processInbox() + world.model.open(recordName(sealed)) + XCTAssertEqual(world.model.openedRequest, OpenedRequest(id: recordName(sealed))) + XCTAssertNil(world.model.opening, "the card exists, so nothing loads") + } + + // MARK: Banners and this iPhone + + func testTheNotificationAuthorizationIsReadAtLaunchAndWhenTheAppBecomesActive() async throws { + XCTAssertEqual(world.model.notificationAuthorization, .allowed) + XCTAssertFalse(world.model.notificationsOff) + world.notifications.authorizationState = .denied + await world.model.sceneBecameActive() + XCTAssertTrue(world.model.notificationsOff) + let relaunched = AppModel(environment: world.environment) + await relaunched.start() + XCTAssertEqual(relaunched.notificationAuthorization, .denied) + world.notifications.authorizationState = .allowed + await world.model.sceneBecameActive() + XCTAssertFalse(world.model.notificationsOff) + } + + func testTheWelcomeReadsTheAnswerToItsNotificationPrompt() async { + let fresh = TestWorld() + fresh.notifications.authorizationState = .denied + await fresh.setUpPhone() + XCTAssertEqual(fresh.notifications.authorizationRequests, 1) + XCTAssertTrue(fresh.model.notificationsOff) + } + + /// While a banner shows, the empty state's capsule says the Macs cannot + /// reach this iPhone. + func testTheCapsuleFollowsTheBanners() { + XCTAssertFalse(RequestsContent.macsCannotReach(accountNotice: nil, notificationsOff: false)) + XCTAssertTrue(RequestsContent.macsCannotReach(accountNotice: nil, notificationsOff: true)) + for notice in [AccountNotice.signedOut, .restricted, .unavailable] { + XCTAssertTrue(RequestsContent.macsCannotReach(accountNotice: notice, notificationsOff: false)) + } + } + + func testTheApprovingMacCountLeavesOutAMacWithoutTheFlag() async throws { + XCTAssertEqual(world.model.approvingMacCount, 1) + try await world.pair(world.makeMac(name: "Office Mac")) + XCTAssertEqual(world.model.approvingMacCount, 2) + try await world.storeWithoutApprovalFlag() + XCTAssertEqual(world.model.pairedMacs.count, 2) + XCTAssertEqual(world.model.approvingMacCount, 1) + } + + func testTheLastDeliveryCheckIsTheLatestAnswered() async throws { + XCTAssertNil(world.model.lastDeliveryCheck) + let phoneID = try world.phone.deviceID + _ = try await world.mac.sendDeliveryCheck(to: phoneID) + world.clock.advance(by: 3) + await world.model.becameActive() + XCTAssertEqual(world.model.lastDeliveryCheck, now) + } + + func testTheFootnoteNamesTouchIDOnATouchIDPhone() async { + XCTAssertEqual(world.model.biometryKind, .faceID) + let touch = TestWorld() + touch.biometry.current = .enrolled(.touchID) + await touch.setUpPhone() + XCTAssertEqual(touch.model.biometryKind, .touchID) + } +} diff --git a/iOS/AskKeyiOSKitTests/RenderChrome.swift b/iOS/AskKeyiOSKitTests/RenderChrome.swift new file mode 100644 index 00000000..bc136be8 --- /dev/null +++ b/iOS/AskKeyiOSKitTests/RenderChrome.swift @@ -0,0 +1,114 @@ +import SwiftUI +@testable import AskKeyiOSKit + +/// iOS draws the navigation bar and the tab bar itself, so `ImageRenderer` +/// cannot capture them. These stand-ins lay out what the system shows +/// around a tab's real content, with the tabs' own names and symbols, for +/// the wording and layout review: the large title, the optional **+**, and +/// the tab bar with the Requests badge. The content is laid out as +/// `tabScaffold()` lays it out in its scroll view: at least as tall as the +/// visible area between the bars, and taller when it needs to be, which +/// makes a taller image. +struct TabScreenStandIn: View { + /// An iPhone screen's height without the status bar, the navigation bar + /// with its large title, and the tab bar. + static var visibleHeight: CGFloat { 852 - 147 - 90 } + + let tab: HomeTab + var badge = 0 + var showsAdd = false + @ViewBuilder var content: Content + + var body: some View { + VStack(spacing: 0) { + HStack { + Spacer() + if showsAdd { + Image(systemName: "plus") + .font(.title3.weight(.medium)) + .frame(width: 44, height: 44) + .background(Circle().fill(Color(uiColor: .systemBackground))) + .shadow(color: .black.opacity(0.08), radius: 6, y: 2) + } + } + .frame(height: 44) + .padding(.horizontal, 16) + .padding(.top, 54) + Text(tab.title, bundle: .kit) + .font(.largeTitle.bold()) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 20) + .padding(.bottom, 8) + content + .frame(maxWidth: .infinity, minHeight: Self.visibleHeight, alignment: .top) + .fixedSize(horizontal: false, vertical: true) + TabBarStandIn(selected: tab, badge: badge) + .padding(.horizontal, 24) + .padding(.bottom, 28) + } + } +} + +/// The tab bar as iOS draws it: three tabs in a capsule, the selected one +/// tinted and filled, the Requests tab with its badge. +private struct TabBarStandIn: View { + let selected: HomeTab + let badge: Int + + var body: some View { + HStack(spacing: 0) { + ForEach(HomeTab.allCases, id: \.self) { tab in + VStack(spacing: 3) { + Image(systemName: tab.symbol) + .symbolVariant(.fill) + .font(.system(size: 20, weight: .medium)) + .frame(height: 26) + .overlay(alignment: .topTrailing) { + if tab == .requests, badge > 0 { + Text(verbatim: String(badge)) + .font(.caption2.bold()) + .foregroundStyle(.white) + .frame(minWidth: 18, minHeight: 18) + .background(Circle().fill(.red)) + .offset(x: 10, y: -6) + } + } + Text(tab.title, bundle: .kit) + .font(.system(size: 10, weight: .semibold)) + } + .foregroundStyle(tab == selected ? Color.accentColor : Color.primary) + .frame(maxWidth: .infinity, minHeight: 54) + .background(Capsule().fill(tab == selected ? Color(uiColor: .systemFill) : .clear).padding(4)) + } + } + .padding(4) + .background(Capsule().fill(Color(uiColor: .systemBackground))) + .shadow(color: .black.opacity(0.1), radius: 12, y: 4) + } +} + +/// A screen pushed in a tab's navigation, with the system's back button. +struct PushedScreenStandIn: View { + @ViewBuilder var content: Content + + var body: some View { + VStack(spacing: 0) { + HStack { + Image(systemName: "chevron.backward") + .font(.title3.weight(.medium)) + .frame(width: 44, height: 44) + .background(Circle().fill(Color(uiColor: .systemBackground))) + .shadow(color: .black.opacity(0.08), radius: 6, y: 2) + Spacer() + } + .frame(height: 44) + .padding(.horizontal, 16) + .padding(.top, 54) + .padding(.bottom, 8) + content + .fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + } + .frame(minHeight: 852, alignment: .top) + } +} diff --git a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift index e4f40cdd..a6d91681 100644 --- a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift +++ b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift @@ -78,26 +78,6 @@ final class ScreenRenderTests: XCTestCase { try render("10-pairing-paired", PairingResultContent(outcome: .paired(macName: Self.mac), onDone: {})) } - func testPairedMacs() throws { - let row = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, lastReachedAt: nil, isApprover: true) - try render("11-paired-macs-one-mac", - PairedMacsContent(rows: [row], accountNotice: nil, listNotice: nil, records: [], onPair: {}, - onSelect: { _ in }, onDismissNotice: {})) - let reached = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, - lastReachedAt: Self.pairedAt.addingTimeInterval(600), isApprover: true) - let records = [ - DeliveryRecord(recordName: "a", arrivedAt: Self.pairedAt.addingTimeInterval(300), source: .polling), - DeliveryRecord(recordName: "b", arrivedAt: Self.pairedAt.addingTimeInterval(600), source: .push), - ] - try render("12-paired-macs-reached", - PairedMacsContent(rows: [reached], accountNotice: nil, - listNotice: .removed(name: "Office Mac", macWasTold: true), records: records, - onPair: {}, onSelect: { _ in }, onDismissNotice: {})) - try render("13-paired-macs-empty-signed-out", - PairedMacsContent(rows: [], accountNotice: .signedOut, listNotice: .removedByMac(name: Self.mac), - records: [], onPair: {}, onSelect: { _ in }, onDismissNotice: {})) - } - func testUnusableIdentity() throws { try render("14-unusable-identity", UnusableIdentityContent(isResetting: false, resetFailed: false, onReset: {})) } @@ -112,10 +92,10 @@ final class ScreenRenderTests: XCTestCase { deliveryRows: [ApprovalDeliveryRow(kind: .environmentVariable, label: "", variable: "GITHUB_TOKEN")], offers: .all, timedDuration: 1_800) - private static func card(_ display: RequestDisplay = display, decision: ApprovalDecisionCode? = nil, - isSent: Bool = false, outcome: RequestOutcome? = nil, isGone: Bool = false, - isChecking: Bool = false, secondsLeft: TimeInterval = 272) -> RequestCard { - RequestCard(id: UUID().uuidString, macID: "mac", macName: mac, macPairedAt: pairedAt, display: display, + private static func card(_ display: RequestDisplay = display, macName: String = mac, + decision: ApprovalDecisionCode? = nil, isSent: Bool = false, outcome: RequestOutcome? = nil, + isGone: Bool = false, isChecking: Bool = false, secondsLeft: TimeInterval = 272) -> RequestCard { + RequestCard(id: UUID().uuidString, macID: "mac", macName: macName, macPairedAt: pairedAt, display: display, countdownEnd: now.addingTimeInterval(secondsLeft), decision: decision, isSent: isSent, outcome: outcome, isGone: isGone, isChecking: isChecking) } @@ -127,19 +107,6 @@ final class ScreenRenderTests: XCTestCase { .padding(20)) } - /// The second Mac was paired before #336 without approval: its row is - /// the only one marked. - func testRequestsHome() throws { - let rows = [PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, - lastReachedAt: Self.pairedAt.addingTimeInterval(600), isApprover: true), - PairedMacRow(id: "office", name: "Office Mac", pairedAt: Self.pairedAt, lastReachedAt: nil)] - try render("15-requests-home", - PairedMacsContent(rows: rows, accountNotice: nil, listNotice: nil, records: [], hasRequests: true, - onPair: {}, onSelect: { _ in }, onDismissNotice: {}) { - RequestCardContent(card: Self.card(), now: Self.now, onDecide: { _ in }, onDismiss: {}) - }) - } - func testRequestCard() throws { try renderCard("16-request-card", Self.card()) try renderCard("17-request-details", Self.card(), details: true) @@ -202,24 +169,87 @@ final class ScreenRenderTests: XCTestCase { }) } - /// #342: the status line, Rename and Remove; only a Mac paired before - /// #336 without approval lacks the flag. + /// #342's status line, Rename and Remove, in #346's grouped layout; only + /// a Mac paired before #336 without approval lacks the flag. func testMacDetail() throws { let approving = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, - lastReachedAt: Self.pairedAt.addingTimeInterval(600), isApprover: true) - try render("34-mac-detail-approving", MacDetailContent(row: approving, onRename: {}, onRemove: {})) - let withoutFlag = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, - lastReachedAt: Self.pairedAt.addingTimeInterval(600)) - try render("35-mac-detail-without-approval-flag", MacDetailContent(row: withoutFlag, onRename: {}, onRemove: {})) + lastReachedAt: Self.now.addingTimeInterval(-120), isApprover: true) + try render("34-mac-detail-approving", PushedScreenStandIn { + MacDetailContent(row: approving, now: Self.now, onRename: {}, onRemove: {}) + }) + let withoutFlag = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, lastReachedAt: nil) + try render("35-mac-detail-without-approval-flag", PushedScreenStandIn { + MacDetailContent(row: withoutFlag, now: Self.now, onRename: {}, onRemove: {}) + }) try render("36-mac-detail-remove-confirmation", ActionSheetStandIn(title: MacRemovalText.title(Self.mac), message: MacRemovalText.message, action: MacRemovalText.confirm) { - MacDetailContent(row: approving, onRename: {}, onRemove: {}) + PushedScreenStandIn { MacDetailContent(row: approving, now: Self.now, onRename: {}, onRemove: {}) } }) // A failed removal leaves the entry, which this process refuses. - try render("37-mac-detail-rename-and-removal-failed", - MacDetailContent(row: withoutFlag, renameProblem: .duplicate("Office Mac"), removalFailed: true, - onRename: {}, onRemove: {})) + try render("37-mac-detail-rename-and-removal-failed", PushedScreenStandIn { + MacDetailContent(row: withoutFlag, now: Self.now, renameProblem: .duplicate("Office Mac"), + removalFailed: true, onRename: {}, onRemove: {}) + }) + } + + // MARK: Home (#346) + + private static let stagingDisplay = RequestDisplay( + requesterName: "Claude Code", purpose: "", credentialName: "Staging API", commandLine: "npm run deploy:staging", + workingDirectory: "~/src/site", executableName: "npm", + deliveryRows: [ApprovalDeliveryRow(kind: .environmentVariable, label: "", variable: "STAGING_API_KEY")]) + + private func requests(_ cards: [RequestCard], hasMacs: Bool = true, accountNotice: AccountNotice? = nil, + notificationsOff: Bool = false) -> some View { + TabScreenStandIn(tab: .requests, badge: cards.filter { $0.phase(at: Self.now) == .pending }.count) { + RequestsContent(cards: cards, now: Self.now, hasMacs: hasMacs, approvingMacs: 2, accountNotice: accountNotice, + notificationsOff: notificationsOff, onOpen: { _ in }, onPair: {}, onOpenSettings: { _ in }) + } + } + + /// One request under a minute, in orange, and one whose decision was + /// sent; the badge counts only the first. + func testRequestsTab() throws { + try render("44-requests-two-requests", + requests([Self.card(secondsLeft: 48), + Self.card(Self.stagingDisplay, macName: "Office Mac", decision: .allowOnce, isSent: true, + secondsLeft: 236)])) + try render("45-requests-empty", requests([])) + try render("46-requests-not-paired", requests([], hasMacs: false)) + try render("47-requests-both-banners", requests([], accountNotice: .signedOut, notificationsOff: true)) + } + + func testHistoryTab() throws { + try render("48-history-empty", TabScreenStandIn(tab: .history) { HistoryContent() }) + } + + private static let macRows = [ + PairedMacRow(id: "mac", name: mac, pairedAt: pairedAt, lastReachedAt: now.addingTimeInterval(-120), isApprover: true), + PairedMacRow(id: "office", name: "Office Mac", pairedAt: pairedAt, lastReachedAt: nil, isApprover: true), + ] + + private func macs(_ rows: [PairedMacRow], notice: ListNotice? = nil, accountNotice: AccountNotice? = nil, + notificationsOff: Bool = false, + lastCheck: Date? = ScreenRenderTests.now.addingTimeInterval(-60)) -> some View { + TabScreenStandIn(tab: .macs, showsAdd: true) { + MacsContent(rows: rows, listNotice: notice, accountNotice: accountNotice, notificationsOff: notificationsOff, + lastDeliveryCheck: lastCheck, version: "1.0 (12)", now: Self.now, onPair: {}, onSelect: { _ in }, + onDismissNotice: {}) + } + } + + func testMacsTab() throws { + try render("49-macs", macs(Self.macRows)) + try render("50-macs-removal-notice", macs([Self.macRows[1]], notice: .removed(name: Self.mac, macWasTold: true))) + // The exceptions: a Mac paired before #336 without approval, a + // notice the Mac could not get, iCloud and notifications off. + let withoutFlag = PairedMacRow(id: "office", name: "Office Mac", pairedAt: Self.pairedAt, + lastReachedAt: Self.now.addingTimeInterval(-3_600)) + try render("51-macs-problems", + macs([Self.macRows[0], withoutFlag], notice: .removed(name: "Old Mac", macWasTold: false), + accountNotice: .signedOut, notificationsOff: true, lastCheck: nil)) + try render("52-macs-empty", macs([])) } func testPrivacyCover() throws { diff --git a/scripts/build-ios.sh b/scripts/build-ios.sh index 60693551..3f5358f8 100755 --- a/scripts/build-ios.sh +++ b/scripts/build-ios.sh @@ -85,7 +85,7 @@ for catalog in (kit, app, extension): problems.append(f'{catalog.relative_to(root)}: "{key}" needs English and Simplified Chinese') elif len({tuple(sorted(placeholder.findall(unit['value']))) for unit in units} | {tuple(sorted(placeholder.findall(key)))}) != 1: problems.append(f'{catalog.relative_to(root)}: "{key}" has mismatched placeholders') -literal = re.compile(r'"((?:common|welcome|scanner|pairing|list|unusable|request|approver|mac)\.[A-Za-z0-9.]+)((?: \\\([^"]*?\))*)"') +literal = re.compile(r'"((?:common|welcome|scanner|pairing|list|unusable|request|approver|mac|tab|history)\.[A-Za-z0-9.]+)((?: \\\([^"]*?\))*)"') for source in sorted((root / 'AskKeyiOSKit').rglob('*.swift')): for match in literal.finditer(source.read_text(encoding='utf-8')): key = match.group(1) + ' %@' * match.group(2).count('\\(') From 91aaf0e80e7cf3e1f3f2b68b9fa4df7bffe521f5 Mon Sep 17 00:00:00 2001 From: sudoHG Date: Mon, 16 Nov 2026 10:03:31 +0800 Subject: [PATCH 2/4] Address the first review round of the iPhone tabs (#346) Show a notification in front only for a request the notification extension verified, so the delivery check after pairing stays silent. Track arrivals in the model so requests reopened at launch are not highlighted and a request that arrives on another tab stays highlighted until the Requests tab shows it. Leave a card that is still being checked out of the badge, show Notifications as On only when allowed, and hide the capsule when no Mac can send requests. Drop the Remove footer so #342's wording stays only in its confirmation, make Rename a tinted action, read the time left to VoiceOver as a duration, and name the problem in each Open Settings hint. Render every new string. --- iOS/AskKeyiOSKit/App/AppModel+Macs.swift | 21 +++++- iOS/AskKeyiOSKit/App/AppModel.swift | 10 ++- iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift | 20 ++++-- .../Resources/Localizable.xcstrings | 19 +----- iOS/AskKeyiOSKit/Views/Components.swift | 1 + iOS/AskKeyiOSKit/Views/MacDetailView.swift | 22 +++---- iOS/AskKeyiOSKit/Views/MacsView.swift | 33 ++++++---- iOS/AskKeyiOSKit/Views/RequestsView.swift | 51 +++++++------- iOS/AskKeyiOSKitTests/HomeTests.swift | 66 ++++++++++++++++++- iOS/AskKeyiOSKitTests/ScreenRenderTests.swift | 24 +++++-- 10 files changed, 184 insertions(+), 83 deletions(-) diff --git a/iOS/AskKeyiOSKit/App/AppModel+Macs.swift b/iOS/AskKeyiOSKit/App/AppModel+Macs.swift index 81aa5056..c09f2bb4 100644 --- a/iOS/AskKeyiOSKit/App/AppModel+Macs.swift +++ b/iOS/AskKeyiOSKit/App/AppModel+Macs.swift @@ -113,9 +113,11 @@ extension AppModel { requests.filter { !$0.phase(at: now).isFinished } } - /// The Requests tab's badge: the requests that can still be decided. + /// The Requests tab's badge: the requests that can still be decided. A + /// card fetched by name for a tapped notification counts once the zone + /// poll after that fetch showed it can be decided (#337). public func decidableRequestCount(at now: Date) -> Int { - requests.filter { $0.phase(at: now) == .pending }.count + requests.filter { $0.phase(at: now) == .pending && !$0.isChecking }.count } /// When the badge can next change without a new card: each undecided @@ -139,6 +141,21 @@ extension AppModel { deliveryRecords.map(\.arrivedAt).max() } + /// Keeps the arrivals current: a card that appears after launch reopened + /// the stored requests arrived, whichever tab shows; one that leaves is + /// no longer highlighted. + func noteArrivals(after previous: [RequestCard]) { + let current = Set(requests.map(\.id)) + var unseen = unseenArrivals.intersection(current) + if storedRequestsRestored { unseen.formUnion(current.subtracting(previous.map(\.id))) } + if unseen != unseenArrivals { unseenArrivals = unseen } + } + + /// The Requests tab showed these rows highlighted for a moment. + public func markArrivalsSeen(_ ids: Set) { + unseenArrivals.subtract(ids) + } + /// The scene became active: read the notification authorization again, /// since the person may have changed it in Settings, then collect the /// pushes and process the inbox. diff --git a/iOS/AskKeyiOSKit/App/AppModel.swift b/iOS/AskKeyiOSKit/App/AppModel.swift index b79c4077..a2be1833 100644 --- a/iOS/AskKeyiOSKit/App/AppModel.swift +++ b/iOS/AskKeyiOSKit/App/AppModel.swift @@ -20,7 +20,12 @@ public final class AppModel { /// The pairing flow while its sheet is open. public var pairing: PairingFlowModel? /// Request cards: pending ones first, by time left, then finished ones. - public internal(set) var requests: [RequestCard] = [] + public internal(set) var requests: [RequestCard] = [] { + didSet { noteArrivals(after: oldValue) } + } + /// Requests that arrived after launch reopened the stored ones and whose + /// rows the Requests tab has not shown yet; those rows are highlighted. + public internal(set) var unseenArrivals: Set = [] /// The request whose decision is being built, with its Face ID prompt. public internal(set) var decidingRequest: String? public internal(set) var decisionProblems: [String: DecisionProblem] = [:] @@ -92,6 +97,8 @@ public final class AppModel { @ObservationIgnored var seenPairings: Set? /// The list as last read, for the Macs' names on the cards. @ObservationIgnored var knownList: PairedDeviceList? + /// Launch reopened the stored requests; cards that appear from now on arrived. + @ObservationIgnored var storedRequestsRestored = false @ObservationIgnored private var accountWatch: Task? @ObservationIgnored private var started = false @@ -179,6 +186,7 @@ public final class AppModel { watchAccount() await refreshList() await restoreApprovals(services) + storedRequestsRestored = true } // MARK: Welcome diff --git a/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift b/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift index d57d81a7..22629d39 100644 --- a/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift +++ b/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift @@ -28,12 +28,20 @@ public final class AskKeyAppDelegate: NSObject, UIApplicationDelegate, UNUserNot } } - /// How a notification shows while the app is in front: the system - /// banner, in Notification Center and with its sound, as when the app is - /// not (decision 8 of #344). - static let foregroundPresentation: UNNotificationPresentationOptions = [.banner, .list, .sound] + /// The thread the notification extension gives only a request it + /// verified from a Mac this iPhone approves for (`NotificationProcessor`). + static let verifiedRequestThreadPrefix = "mac_" - /// A push for the app in front: the system banner shows as usual and the + /// How a notification shows while the app is in front (decision 8 of + /// #344): a request the extension verified shows its banner, in + /// Notification Center and with its sound, as when the app is not in + /// front; any other push, such as the delivery check after pairing, + /// stays silent as before. Only the presentation depends on it. + static func foregroundPresentation(threadIdentifier: String) -> UNNotificationPresentationOptions { + threadIdentifier.hasPrefix(verifiedRequestThreadPrefix) ? [.banner, .list, .sound] : [] + } + + /// A push for the app in front: a request's banner shows as usual and the /// app fetches at once. The request's page does not open by itself; the /// Requests tab's badge and its highlighted row show the new request. public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, @@ -41,7 +49,7 @@ public final class AskKeyAppDelegate: NSObject, UIApplicationDelegate, UNUserNot let userInfo = notification.request.content.userInfo let arrivedAt = notification.date let identifier = notification.request.identifier - completionHandler(Self.foregroundPresentation) + completionHandler(Self.foregroundPresentation(threadIdentifier: notification.request.content.threadIdentifier)) Task { @MainActor in await model.receivedPush(userInfo: userInfo, arrivedAt: arrivedAt, notificationIdentifier: identifier) } diff --git a/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings b/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings index 0698c3ff..e00faf7c 100644 --- a/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings +++ b/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings @@ -98,7 +98,7 @@ "zh-Hans": { "stringUnit": { "state": "translated", - "value": "发到这台 iPhone 的请求处理后会记在这里,保留 30 天。" + "value": "发到这台 iPhone 的请求结束后会记在这里,保留 30 天。" } } } @@ -681,23 +681,6 @@ } } }, - "mac.remove.footer": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "This iPhone stops approving this Mac's requests at once and drops the pending ones." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "这台 iPhone 会立即停止审批这台 Mac 的请求,并丢弃待处理的请求。" - } - } - } - }, "mac.rename": { "extractionState": "manual", "localizations": { diff --git a/iOS/AskKeyiOSKit/Views/Components.swift b/iOS/AskKeyiOSKit/Views/Components.swift index 78b23301..fe762c72 100644 --- a/iOS/AskKeyiOSKit/Views/Components.swift +++ b/iOS/AskKeyiOSKit/Views/Components.swift @@ -264,6 +264,7 @@ struct BannerRow: View { .font(.body) .fixedSize(horizontal: false, vertical: true) Button(action: onOpenSettings) { Text("common.openSettings", bundle: .kit) } + .accessibilityHint(text) .buttonStyle(.bordered) .controlSize(.small) .buttonBorderShape(.capsule) diff --git a/iOS/AskKeyiOSKit/Views/MacDetailView.swift b/iOS/AskKeyiOSKit/Views/MacDetailView.swift index dd0e126f..ce4d38a8 100644 --- a/iOS/AskKeyiOSKit/Views/MacDetailView.swift +++ b/iOS/AskKeyiOSKit/Views/MacDetailView.swift @@ -108,14 +108,12 @@ struct MacDetailContent: View { } GroupedSection { Button(action: onRename) { - HStack { - Text("mac.rename", bundle: .kit).foregroundStyle(.primary) - Spacer(minLength: 8) - RowChevron() - } - .padding(.horizontal, 16) - .padding(.vertical, 11) - .frame(minHeight: GroupedMetrics.rowMinHeight) + Text("mac.rename", bundle: .kit) + .foregroundStyle(Color.accentColor) + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 16) + .padding(.vertical, 11) + .frame(minHeight: GroupedMetrics.rowMinHeight) } .buttonStyle(GroupedRowButtonStyle()) } footer: { @@ -136,11 +134,9 @@ struct MacDetailContent: View { } .buttonStyle(GroupedRowButtonStyle()) } footer: { - VStack(alignment: .leading, spacing: 6) { - if removalFailed { - Text("list.notice.removalFailed", bundle: .kit).foregroundStyle(.orange) - } - Text("mac.remove.footer", bundle: .kit) + // What removing does is #342's confirmation, word for word. + if removalFailed { + Text("list.notice.removalFailed", bundle: .kit).foregroundStyle(.orange) } } } diff --git a/iOS/AskKeyiOSKit/Views/MacsView.swift b/iOS/AskKeyiOSKit/Views/MacsView.swift index a06542bb..568e0d39 100644 --- a/iOS/AskKeyiOSKit/Views/MacsView.swift +++ b/iOS/AskKeyiOSKit/Views/MacsView.swift @@ -10,7 +10,7 @@ struct MacsView: View { var body: some View { TimelineView(.periodic(from: .now, by: 30)) { context in MacsContent(rows: model.pairedMacs, listNotice: model.listNotice, accountNotice: model.accountNotice, - notificationsOff: model.notificationsOff, lastDeliveryCheck: model.lastDeliveryCheck, + notifications: model.notificationAuthorization, lastDeliveryCheck: model.lastDeliveryCheck, version: AppVersion.current, now: context.date, onPair: model.startPairing, onSelect: { selectedMac = $0.id }, onDismissNotice: { model.listNotice = nil }) } @@ -30,8 +30,8 @@ struct MacsView: View { } .onChange(of: model.openedRequest) { _, opened in // A tapped notification's page opens over the home; the Mac's - // detail, with its dialogs, closes first. - if opened != nil { selectedMac = nil } + // detail on screen, with its dialogs, closes first. + if opened != nil, model.selectedTab == .macs { selectedMac = nil } } } } @@ -53,7 +53,8 @@ struct MacsContent: View { let rows: [PairedMacRow] let listNotice: ListNotice? let accountNotice: AccountNotice? - let notificationsOff: Bool + /// As last read; nil before the first read. + let notifications: NotificationAuthorization? let lastDeliveryCheck: Date? let version: String let now: Date @@ -81,13 +82,23 @@ struct MacsContent: View { Text("list.footer", bundle: .kit) } } - ThisIPhoneSection(accountNotice: accountNotice, notificationsOff: notificationsOff, + ThisIPhoneSection(accountNotice: accountNotice, notificationsOn: Self.notificationsOn(notifications), lastDeliveryCheck: lastDeliveryCheck, version: version) } .padding(.horizontal, 16) .padding(.top, 8) .padding(.bottom, 24) } + + /// The Notifications row: on only when allowed, off when denied or never + /// answered, nothing before the first read. + static func notificationsOn(_ authorization: NotificationAuthorization?) -> Bool? { + switch authorization { + case .allowed?: return true + case .denied?, .notDetermined?: return false + case nil: return nil + } + } } /// A Mac's row: its name, when this iPhone last heard from it, and only for @@ -191,7 +202,7 @@ struct RemovalNoticeRow: View { /// check, and that no credential value is kept here, with the version. private struct ThisIPhoneSection: View { let accountNotice: AccountNotice? - let notificationsOff: Bool + let notificationsOn: Bool? let lastDeliveryCheck: Date? let version: String @@ -203,13 +214,13 @@ private struct ThisIPhoneSection: View { iCloudValue } GroupedDivider(leadingInset: GroupedMetrics.symbolInset) - ValueRow(symbol: notificationsOff ? "bell.slash" : "bell") { + ValueRow(symbol: notificationsOn == false ? "bell.slash" : "bell") { Text("list.notifications", bundle: .kit) } value: { - if notificationsOff { - Text("list.notifications.stateOff", bundle: .kit).foregroundStyle(.orange) - } else { - Text("list.notifications.stateOn", bundle: .kit).foregroundStyle(.secondary) + switch notificationsOn { + case true?: Text("list.notifications.stateOn", bundle: .kit).foregroundStyle(.secondary) + case false?: Text("list.notifications.stateOff", bundle: .kit).foregroundStyle(.orange) + case nil: EmptyView() } } GroupedDivider(leadingInset: GroupedMetrics.symbolInset) diff --git a/iOS/AskKeyiOSKit/Views/RequestsView.swift b/iOS/AskKeyiOSKit/Views/RequestsView.swift index d6c2f51a..9cd436bc 100644 --- a/iOS/AskKeyiOSKit/Views/RequestsView.swift +++ b/iOS/AskKeyiOSKit/Views/RequestsView.swift @@ -6,44 +6,36 @@ import UIKit /// for iCloud and notification problems, then the requests that can still /// be decided or wait for the Mac, or an empty state. Tapping a row opens /// the request's page. A request that arrives never opens its page by -/// itself; its row is briefly highlighted instead (decision 8 of #344). +/// itself; its row is highlighted instead, for two seconds once this tab +/// shows it (decision 8 of #344). struct RequestsView: View { @Bindable var model: AppModel @Environment(\.openURL) private var openURL - /// The request IDs as last seen; nil before the first look, so the rows - /// already there when the tab appears are not highlighted. - @State private var seenRequests: Set? - @State private var highlighted: Set = [] var body: some View { TimelineView(.periodic(from: .now, by: 1)) { context in RequestsContent(cards: model.activeRequests(at: context.date), now: context.date, hasMacs: !model.pairedMacs.isEmpty, approvingMacs: model.approvingMacCount, accountNotice: model.accountNotice, notificationsOff: model.notificationsOff, - biometry: model.biometryKind, highlighted: highlighted, + biometry: model.biometryKind, highlighted: model.unseenArrivals, onOpen: { model.open($0.id) }, onPair: model.startPairing, onOpenSettings: openSettings) } .tabScaffold() .refreshable { await model.processInbox() } .navigationTitle(Text(HomeTab.requests.title, bundle: .kit)) .navigationBarTitleDisplayMode(.large) - .onChange(of: model.requests.map(\.id), initial: true) { _, ids in - highlightArrivals(ids) + .task(id: ArrivalWatch(shown: model.selectedTab == .requests, arrivals: model.unseenArrivals)) { + guard model.selectedTab == .requests, !model.unseenArrivals.isEmpty else { return } + let shown = model.unseenArrivals + try? await Task.sleep(for: .seconds(2)) + guard !Task.isCancelled else { return } + withAnimation(.easeOut(duration: 0.8)) { model.markArrivalsSeen(shown) } } } - private func highlightArrivals(_ ids: [String]) { - let current = Set(ids) - let previous = seenRequests - seenRequests = current - guard let previous else { return } - let arrived = current.subtracting(previous) - guard !arrived.isEmpty else { return } - highlighted.formUnion(arrived) - Task { @MainActor in - try? await Task.sleep(for: .seconds(2)) - withAnimation(.easeOut(duration: 0.8)) { highlighted.subtract(arrived) } - } + private struct ArrivalWatch: Equatable { + let shown: Bool + let arrivals: Set } private func openSettings(_ page: SettingsPage) { @@ -92,10 +84,13 @@ struct RequestsContent: View { if cards.isEmpty { Spacer(minLength: 24) if hasMacs { + let cannotReach = Self.macsCannotReach(accountNotice: accountNotice, notificationsOff: notificationsOff) EmptyStateView(symbol: "tray", title: "request.empty.title", detail: "request.empty.detail") { - ReachabilityCapsule(approvingMacs: approvingMacs, - cannotReach: Self.macsCannotReach(accountNotice: accountNotice, - notificationsOff: notificationsOff)) + // Without an approving Mac the Macs tab says why; the + // capsule has nothing true to count. + if cannotReach || approvingMacs > 0 { + ReachabilityCapsule(approvingMacs: approvingMacs, cannotReach: cannotReach) + } } } else { EmptyStateView(symbol: "laptopcomputer", title: "list.empty.title", detail: "list.empty.detail") { @@ -150,6 +145,7 @@ struct RequestRow: View { var isHighlighted = false let onOpen: () -> Void @Environment(\.dynamicTypeSize) private var typeSize + @Environment(\.locale) private var locale var body: some View { Button(action: onOpen) { @@ -172,6 +168,7 @@ struct RequestRow: View { .background(isHighlighted ? Color.accentColor.opacity(0.14) : Color.clear) } .buttonStyle(GroupedRowButtonStyle()) + .accessibilityAddTraits(.updatesFrequently) } @ViewBuilder private var status: some View { @@ -189,9 +186,15 @@ struct RequestRow: View { } .monospacedDigit() .foregroundStyle(seconds < 60 ? Color.orange : Color.secondary) + .accessibilityLabel(Text("request.timeLeft.value \(Self.spoken(seconds, locale: locale))", bundle: .kit)) } } + /// Seconds as VoiceOver reads them, such as "4 minutes, 32 seconds". + static func spoken(_ seconds: Int, locale: Locale) -> String { + Duration.seconds(seconds).formatted(.units(allowed: [.minutes, .seconds], width: .wide).locale(locale)) + } + /// Seconds as minutes and seconds, such as "4:32". static func clock(_ seconds: Int) -> String { String(format: "%d:%02d", seconds / 60, seconds % 60) @@ -207,7 +210,7 @@ struct ReachabilityCapsule: View { var body: some View { HStack(spacing: 8) { Circle() - .fill(cannotReach || approvingMacs == 0 ? Color.orange : Color.green) + .fill(cannotReach ? Color.orange : Color.green) .frame(width: 8, height: 8) .accessibilityHidden(true) text diff --git a/iOS/AskKeyiOSKitTests/HomeTests.swift b/iOS/AskKeyiOSKitTests/HomeTests.swift index 88fe2e50..da78f4e2 100644 --- a/iOS/AskKeyiOSKitTests/HomeTests.swift +++ b/iOS/AskKeyiOSKitTests/HomeTests.swift @@ -66,10 +66,27 @@ final class HomeTests: XCTestCase { XCTAssertEqual(world.model.decidableCountChanges, [pending.countdownEnd]) } + /// A card fetched by name for a tapped notification cannot be decided + /// until the zone poll after that fetch ran (#337), so the badge leaves + /// it out while the row still lists it. + func testTheBadgeLeavesOutACardStillBeingChecked() throws { + let display = RequestDisplay(requesterName: "Codex", purpose: "", credentialName: "GitHub Token", + commandLine: "./deploy.sh", workingDirectory: "", executableName: "deploy.sh", + deliveryRows: []) + func card(_ id: String, isChecking: Bool) -> RequestCard { + RequestCard(id: id, macID: "mac", macName: TestWorld.macName, macPairedAt: now, display: display, + countdownEnd: now.addingTimeInterval(200), isChecking: isChecking) + } + world.model.requests = [card("checking", isChecking: true), card("checked", isChecking: false)] + XCTAssertEqual(world.model.activeRequests(at: now).count, 2) + XCTAssertEqual(world.model.decidableRequestCount(at: now), 1) + } + /// Decision 8 of #344: in front, the notification shows as a banner, the /// badge counts the request, and neither its page nor the tab changes. func testARequestArrivingInFrontNeverOpensItsPage() async throws { - XCTAssertEqual(AskKeyAppDelegate.foregroundPresentation, [.banner, .list, .sound]) + XCTAssertEqual(AskKeyAppDelegate.foregroundPresentation(threadIdentifier: "mac_" + world.macIdentity.deviceID.text), + [.banner, .list, .sound]) world.model.selectedTab = .macs let sealed = try await world.sendRequest() await world.model.receivedPush(userInfo: TestWorld.alertPush(for: try world.phone.deviceID, @@ -82,6 +99,40 @@ final class HomeTests: XCTestCase { XCTAssertEqual(world.model.selectedTab, .macs) } + /// Only a request the notification extension verified shows in front; + /// the delivery check after pairing and any other push stay silent. + func testOtherPushesStaySilentInFront() { + XCTAssertEqual(AskKeyAppDelegate.foregroundPresentation(threadIdentifier: ""), []) + XCTAssertEqual(AskKeyAppDelegate.foregroundPresentation(threadIdentifier: "other"), []) + } + + /// A request that arrives is highlighted, whichever tab shows, until the + /// Requests tab has shown it; one that leaves is no longer highlighted. + func testAnArrivingRequestIsHighlightedUntilTheRequestsTabShowsIt() async throws { + world.model.selectedTab = .macs + let first = try await world.sendRequest() + await world.model.processInbox() + XCTAssertEqual(world.model.unseenArrivals, [recordName(first)]) + world.model.markArrivalsSeen([recordName(first)]) + XCTAssertTrue(world.model.unseenArrivals.isEmpty) + + let second = try await world.sendRequest() + await world.model.processInbox() + XCTAssertEqual(world.model.unseenArrivals, [recordName(second)]) + await world.model.removeMac(id: world.macIdentity.deviceID.text) + XCTAssertTrue(world.model.unseenArrivals.isEmpty, "a dropped request is not highlighted") + } + + /// Requests reopened at launch did not just arrive. + func testRequestsReopenedAtLaunchAreNotHighlighted() async throws { + try await world.sendRequest() + await world.model.processInbox() + let relaunched = AppModel(environment: world.environment) + await relaunched.start() + XCTAssertEqual(relaunched.requests.count, 1) + XCTAssertTrue(relaunched.unseenArrivals.isEmpty) + } + /// Tapping a row opens that request's page with its card at once. func testOpeningARowShowsItsCard() async throws { let sealed = try await world.sendRequest() @@ -107,6 +158,18 @@ final class HomeTests: XCTestCase { XCTAssertFalse(world.model.notificationsOff) } + /// The banner shows only when notifications were turned off; the This + /// iPhone row says On only when they are allowed. + func testOnlyAllowedNotificationsShowAsOn() async { + world.notifications.authorizationState = .notDetermined + await world.model.sceneBecameActive() + XCTAssertFalse(world.model.notificationsOff, "Settings has no switch to send the person to yet") + XCTAssertEqual(MacsContent.notificationsOn(.allowed), true) + XCTAssertEqual(MacsContent.notificationsOn(.denied), false) + XCTAssertEqual(MacsContent.notificationsOn(.notDetermined), false) + XCTAssertNil(MacsContent.notificationsOn(nil)) + } + func testTheWelcomeReadsTheAnswerToItsNotificationPrompt() async { let fresh = TestWorld() fresh.notifications.authorizationState = .denied @@ -118,6 +181,7 @@ final class HomeTests: XCTestCase { /// While a banner shows, the empty state's capsule says the Macs cannot /// reach this iPhone. func testTheCapsuleFollowsTheBanners() { + XCTAssertEqual(RequestRow.spoken(272, locale: Locale(identifier: "en")), "4 minutes, 32 seconds") XCTAssertFalse(RequestsContent.macsCannotReach(accountNotice: nil, notificationsOff: false)) XCTAssertTrue(RequestsContent.macsCannotReach(accountNotice: nil, notificationsOff: true)) for notice in [AccountNotice.signedOut, .restricted, .unavailable] { diff --git a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift index a6d91681..25ea449d 100644 --- a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift +++ b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift @@ -200,11 +200,13 @@ final class ScreenRenderTests: XCTestCase { workingDirectory: "~/src/site", executableName: "npm", deliveryRows: [ApprovalDeliveryRow(kind: .environmentVariable, label: "", variable: "STAGING_API_KEY")]) - private func requests(_ cards: [RequestCard], hasMacs: Bool = true, accountNotice: AccountNotice? = nil, - notificationsOff: Bool = false) -> some View { + private func requests(_ cards: [RequestCard], hasMacs: Bool = true, approvingMacs: Int = 2, + accountNotice: AccountNotice? = nil, notificationsOff: Bool = false, + biometry: BiometryKind = .faceID) -> some View { TabScreenStandIn(tab: .requests, badge: cards.filter { $0.phase(at: Self.now) == .pending }.count) { - RequestsContent(cards: cards, now: Self.now, hasMacs: hasMacs, approvingMacs: 2, accountNotice: accountNotice, - notificationsOff: notificationsOff, onOpen: { _ in }, onPair: {}, onOpenSettings: { _ in }) + RequestsContent(cards: cards, now: Self.now, hasMacs: hasMacs, approvingMacs: approvingMacs, + accountNotice: accountNotice, notificationsOff: notificationsOff, biometry: biometry, + onOpen: { _ in }, onPair: {}, onOpenSettings: { _ in }) } } @@ -218,6 +220,11 @@ final class ScreenRenderTests: XCTestCase { try render("45-requests-empty", requests([])) try render("46-requests-not-paired", requests([], hasMacs: false)) try render("47-requests-both-banners", requests([], accountNotice: .signedOut, notificationsOff: true)) + // A decision stored but not yet saved, the Touch ID footnote, and one Mac. + try render("53-requests-sending-touch-id", + requests([Self.card(Self.stagingDisplay, macName: "Office Mac", decision: .deny, secondsLeft: 236), + Self.card(secondsLeft: 272)], biometry: .touchID)) + try render("54-requests-empty-one-mac", requests([], approvingMacs: 1)) } func testHistoryTab() throws { @@ -230,10 +237,10 @@ final class ScreenRenderTests: XCTestCase { ] private func macs(_ rows: [PairedMacRow], notice: ListNotice? = nil, accountNotice: AccountNotice? = nil, - notificationsOff: Bool = false, + notifications: NotificationAuthorization = .allowed, lastCheck: Date? = ScreenRenderTests.now.addingTimeInterval(-60)) -> some View { TabScreenStandIn(tab: .macs, showsAdd: true) { - MacsContent(rows: rows, listNotice: notice, accountNotice: accountNotice, notificationsOff: notificationsOff, + MacsContent(rows: rows, listNotice: notice, accountNotice: accountNotice, notifications: notifications, lastDeliveryCheck: lastCheck, version: "1.0 (12)", now: Self.now, onPair: {}, onSelect: { _ in }, onDismissNotice: {}) } @@ -248,8 +255,11 @@ final class ScreenRenderTests: XCTestCase { lastReachedAt: Self.now.addingTimeInterval(-3_600)) try render("51-macs-problems", macs([Self.macRows[0], withoutFlag], notice: .removed(name: "Old Mac", macWasTold: false), - accountNotice: .signedOut, notificationsOff: true, lastCheck: nil)) + accountNotice: .signedOut, notifications: .denied, lastCheck: nil)) try render("52-macs-empty", macs([])) + // The other iCloud states; notifications never answered read Off. + try render("55-macs-icloud-restricted", macs(Self.macRows, accountNotice: .restricted, notifications: .notDetermined)) + try render("56-macs-icloud-unavailable", macs(Self.macRows, accountNotice: .unavailable)) } func testPrivacyCover() throws { From e78dc6a0d3a573496a80a3c14219fb3ba4f5ff8d Mon Sep 17 00:00:00 2001 From: sudoHG Date: Mon, 16 Nov 2026 10:13:03 +0800 Subject: [PATCH 3/4] Address the second review round of the iPhone tabs (#346) Show every notification in front as decision 8 specifies again, so a request the extension could not verify still gets its banner. Center the Mac detail's status line and give the not-approving warning orange text. Shorten long requester and Mac names in a Requests row so they cannot push the credential out of its two lines. Say nothing about iCloud on This iPhone before the first account check. Give Open Settings the regular size and the removal notice's dismiss button a 44-point target, draw the tab bar under the Mac detail renders, and render the Requests tab at an accessibility text size. --- iOS/AskKeyiOSKit/App/AppModel.swift | 4 +++- iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift | 21 +++++++------------ iOS/AskKeyiOSKit/Views/Components.swift | 1 - iOS/AskKeyiOSKit/Views/MacDetailView.swift | 8 ++++--- iOS/AskKeyiOSKit/Views/MacsView.swift | 14 +++++++++++-- iOS/AskKeyiOSKit/Views/RequestsView.swift | 18 +++++++++++++++- iOS/AskKeyiOSKitTests/HomeTests.swift | 18 ++++++++-------- iOS/AskKeyiOSKitTests/RenderChrome.swift | 7 ++++++- iOS/AskKeyiOSKitTests/ScreenRenderTests.swift | 9 ++++++++ 9 files changed, 68 insertions(+), 32 deletions(-) diff --git a/iOS/AskKeyiOSKit/App/AppModel.swift b/iOS/AskKeyiOSKit/App/AppModel.swift index a2be1833..b9745bc4 100644 --- a/iOS/AskKeyiOSKit/App/AppModel.swift +++ b/iOS/AskKeyiOSKit/App/AppModel.swift @@ -51,7 +51,9 @@ public final class AppModel { @ObservationIgnored let environment: AppEnvironment @ObservationIgnored var services: DeviceServices? @ObservationIgnored var pendingSetup: PendingSetup? - @ObservationIgnored var accountChecked = false + /// The iCloud account was checked since the identity was restored or + /// created; observed, so This iPhone says nothing about iCloud before. + var accountChecked = false @ObservationIgnored var pushHints: [String: PushHint] = [:] /// Pushes that arrived before the identity was restored at launch. @ObservationIgnored var earlyPushes: [EarlyPush] = [] diff --git a/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift b/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift index 22629d39..694ed0ac 100644 --- a/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift +++ b/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift @@ -28,20 +28,13 @@ public final class AskKeyAppDelegate: NSObject, UIApplicationDelegate, UNUserNot } } - /// The thread the notification extension gives only a request it - /// verified from a Mac this iPhone approves for (`NotificationProcessor`). - static let verifiedRequestThreadPrefix = "mac_" + /// How a notification shows while the app is in front: the system + /// banner, in Notification Center and with its sound, as when the app is + /// not (decision 8 of #344). Whatever the extension could verify, the + /// notification shows as it would in the background. + static let foregroundPresentation: UNNotificationPresentationOptions = [.banner, .list, .sound] - /// How a notification shows while the app is in front (decision 8 of - /// #344): a request the extension verified shows its banner, in - /// Notification Center and with its sound, as when the app is not in - /// front; any other push, such as the delivery check after pairing, - /// stays silent as before. Only the presentation depends on it. - static func foregroundPresentation(threadIdentifier: String) -> UNNotificationPresentationOptions { - threadIdentifier.hasPrefix(verifiedRequestThreadPrefix) ? [.banner, .list, .sound] : [] - } - - /// A push for the app in front: a request's banner shows as usual and the + /// A push for the app in front: the banner shows as usual and the /// app fetches at once. The request's page does not open by itself; the /// Requests tab's badge and its highlighted row show the new request. public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, @@ -49,7 +42,7 @@ public final class AskKeyAppDelegate: NSObject, UIApplicationDelegate, UNUserNot let userInfo = notification.request.content.userInfo let arrivedAt = notification.date let identifier = notification.request.identifier - completionHandler(Self.foregroundPresentation(threadIdentifier: notification.request.content.threadIdentifier)) + completionHandler(Self.foregroundPresentation) Task { @MainActor in await model.receivedPush(userInfo: userInfo, arrivedAt: arrivedAt, notificationIdentifier: identifier) } diff --git a/iOS/AskKeyiOSKit/Views/Components.swift b/iOS/AskKeyiOSKit/Views/Components.swift index fe762c72..045c1afa 100644 --- a/iOS/AskKeyiOSKit/Views/Components.swift +++ b/iOS/AskKeyiOSKit/Views/Components.swift @@ -266,7 +266,6 @@ struct BannerRow: View { Button(action: onOpenSettings) { Text("common.openSettings", bundle: .kit) } .accessibilityHint(text) .buttonStyle(.bordered) - .controlSize(.small) .buttonBorderShape(.capsule) } .frame(maxWidth: .infinity, alignment: .leading) diff --git a/iOS/AskKeyiOSKit/Views/MacDetailView.swift b/iOS/AskKeyiOSKit/Views/MacDetailView.swift index ce4d38a8..97597c5a 100644 --- a/iOS/AskKeyiOSKit/Views/MacDetailView.swift +++ b/iOS/AskKeyiOSKit/Views/MacDetailView.swift @@ -163,15 +163,17 @@ struct MacDetailContent: View { .multilineTextAlignment(.center) .fixedSize(horizontal: false, vertical: true) .accessibilityAddTraits(.isHeader) - HStack(alignment: .firstTextBaseline, spacing: 6) { + VStack(spacing: 6) { Image(systemName: row.isApprover ? "checkmark.shield.fill" : "exclamationmark.shield.fill") + .font(.title3) .foregroundStyle(row.isApprover ? Color.green : Color.orange) .accessibilityHidden(true) Text(row.isApprover ? "mac.status.approving" : "mac.status.notApproving", bundle: .kit) - .foregroundStyle(.secondary) + .font(.subheadline) + .foregroundStyle(row.isApprover ? Color.secondary : Color.orange) + .multilineTextAlignment(.center) .fixedSize(horizontal: false, vertical: true) } - .font(.subheadline) .padding(.horizontal, 8) } .frame(maxWidth: .infinity) diff --git a/iOS/AskKeyiOSKit/Views/MacsView.swift b/iOS/AskKeyiOSKit/Views/MacsView.swift index 568e0d39..436040b7 100644 --- a/iOS/AskKeyiOSKit/Views/MacsView.swift +++ b/iOS/AskKeyiOSKit/Views/MacsView.swift @@ -10,7 +10,8 @@ struct MacsView: View { var body: some View { TimelineView(.periodic(from: .now, by: 30)) { context in MacsContent(rows: model.pairedMacs, listNotice: model.listNotice, accountNotice: model.accountNotice, - notifications: model.notificationAuthorization, lastDeliveryCheck: model.lastDeliveryCheck, + accountChecked: model.accountChecked, notifications: model.notificationAuthorization, + lastDeliveryCheck: model.lastDeliveryCheck, version: AppVersion.current, now: context.date, onPair: model.startPairing, onSelect: { selectedMac = $0.id }, onDismissNotice: { model.listNotice = nil }) } @@ -53,6 +54,8 @@ struct MacsContent: View { let rows: [PairedMacRow] let listNotice: ListNotice? let accountNotice: AccountNotice? + /// False until the first account check; This iPhone then shows no iCloud state. + var accountChecked = true /// As last read; nil before the first read. let notifications: NotificationAuthorization? let lastDeliveryCheck: Date? @@ -82,7 +85,8 @@ struct MacsContent: View { Text("list.footer", bundle: .kit) } } - ThisIPhoneSection(accountNotice: accountNotice, notificationsOn: Self.notificationsOn(notifications), + ThisIPhoneSection(accountNotice: accountNotice, accountChecked: accountChecked, + notificationsOn: Self.notificationsOn(notifications), lastDeliveryCheck: lastDeliveryCheck, version: version) } .padding(.horizontal, 16) @@ -170,8 +174,12 @@ struct RemovalNoticeRow: View { Image(systemName: "xmark.circle.fill") .font(.title3) .foregroundStyle(.secondary) + .frame(minWidth: 44, minHeight: 44) + .contentShape(Rectangle()) } .buttonStyle(.plain) + .padding(.vertical, -10) + .padding(.trailing, -10) .accessibilityLabel(Text("common.dismiss", bundle: .kit)) } .padding(16) @@ -202,6 +210,7 @@ struct RemovalNoticeRow: View { /// check, and that no credential value is kept here, with the version. private struct ThisIPhoneSection: View { let accountNotice: AccountNotice? + let accountChecked: Bool let notificationsOn: Bool? let lastDeliveryCheck: Date? let version: String @@ -244,6 +253,7 @@ private struct ThisIPhoneSection: View { @ViewBuilder private var iCloudValue: some View { switch accountNotice { + case nil where !accountChecked: EmptyView() case nil: Text("list.iCloud.signedIn", bundle: .kit).foregroundStyle(.secondary) case .signedOut: Text("list.iCloud.signedOut", bundle: .kit).foregroundStyle(.orange) case .restricted: Text("list.iCloud.restricted", bundle: .kit).foregroundStyle(.orange) diff --git a/iOS/AskKeyiOSKit/Views/RequestsView.swift b/iOS/AskKeyiOSKit/Views/RequestsView.swift index 9cd436bc..82dac90a 100644 --- a/iOS/AskKeyiOSKit/Views/RequestsView.swift +++ b/iOS/AskKeyiOSKit/Views/RequestsView.swift @@ -151,7 +151,7 @@ struct RequestRow: View { Button(action: onOpen) { HStack(spacing: 12) { VStack(alignment: .leading, spacing: 6) { - RequestSentence(card: card) + sentence .font(.body) .foregroundStyle(.primary) .multilineTextAlignment(.leading) @@ -171,6 +171,22 @@ struct RequestRow: View { .accessibilityAddTraits(.updatesFrequently) } + /// The card's sentence, names bold, with the requester's and the Mac's + /// names shortened so that a long name, which the agent chooses, cannot + /// push the credential out of the row; the page shows them in full. + private var sentence: Text { + let requester = card.display.requesterName.isEmpty + ? Text("request.localAgent", bundle: .kit) : Text(verbatim: Self.short(card.display.requesterName)) + let mac = Text(verbatim: Self.short(card.macName)) + return Text("request.title \(requester.bold()) \(mac.bold()) \(Text(verbatim: card.display.credentialName).bold())", + bundle: .kit) + } + + /// A name cut to `limit` characters with an ellipsis. + static func short(_ name: String, limit: Int = 24) -> String { + name.count > limit ? String(name.prefix(limit - 1)) + "…" : name + } + @ViewBuilder private var status: some View { switch card.phase(at: now) { case .sending: diff --git a/iOS/AskKeyiOSKitTests/HomeTests.swift b/iOS/AskKeyiOSKitTests/HomeTests.swift index da78f4e2..25d2dcb6 100644 --- a/iOS/AskKeyiOSKitTests/HomeTests.swift +++ b/iOS/AskKeyiOSKitTests/HomeTests.swift @@ -85,8 +85,7 @@ final class HomeTests: XCTestCase { /// Decision 8 of #344: in front, the notification shows as a banner, the /// badge counts the request, and neither its page nor the tab changes. func testARequestArrivingInFrontNeverOpensItsPage() async throws { - XCTAssertEqual(AskKeyAppDelegate.foregroundPresentation(threadIdentifier: "mac_" + world.macIdentity.deviceID.text), - [.banner, .list, .sound]) + XCTAssertEqual(AskKeyAppDelegate.foregroundPresentation, [.banner, .list, .sound]) world.model.selectedTab = .macs let sealed = try await world.sendRequest() await world.model.receivedPush(userInfo: TestWorld.alertPush(for: try world.phone.deviceID, @@ -99,13 +98,6 @@ final class HomeTests: XCTestCase { XCTAssertEqual(world.model.selectedTab, .macs) } - /// Only a request the notification extension verified shows in front; - /// the delivery check after pairing and any other push stay silent. - func testOtherPushesStaySilentInFront() { - XCTAssertEqual(AskKeyAppDelegate.foregroundPresentation(threadIdentifier: ""), []) - XCTAssertEqual(AskKeyAppDelegate.foregroundPresentation(threadIdentifier: "other"), []) - } - /// A request that arrives is highlighted, whichever tab shows, until the /// Requests tab has shown it; one that leaves is no longer highlighted. func testAnArrivingRequestIsHighlightedUntilTheRequestsTabShowsIt() async throws { @@ -180,6 +172,14 @@ final class HomeTests: XCTestCase { /// While a banner shows, the empty state's capsule says the Macs cannot /// reach this iPhone. + /// A long requester or Mac name is shortened in the row only. + func testARowShortensLongNamesSoTheCredentialStaysVisible() { + XCTAssertEqual(RequestRow.short("Codex"), "Codex") + let long = String(repeating: "a", count: 60) + XCTAssertEqual(RequestRow.short(long).count, 24) + XCTAssertTrue(RequestRow.short(long).hasSuffix("…")) + } + func testTheCapsuleFollowsTheBanners() { XCTAssertEqual(RequestRow.spoken(272, locale: Locale(identifier: "en")), "4 minutes, 32 seconds") XCTAssertFalse(RequestsContent.macsCannotReach(accountNotice: nil, notificationsOff: false)) diff --git a/iOS/AskKeyiOSKitTests/RenderChrome.swift b/iOS/AskKeyiOSKitTests/RenderChrome.swift index bc136be8..3b122c4b 100644 --- a/iOS/AskKeyiOSKitTests/RenderChrome.swift +++ b/iOS/AskKeyiOSKitTests/RenderChrome.swift @@ -87,8 +87,10 @@ private struct TabBarStandIn: View { } } -/// A screen pushed in a tab's navigation, with the system's back button. +/// A screen pushed in a tab's navigation, with the system's back button +/// and the tab bar, which stays visible. struct PushedScreenStandIn: View { + var tab: HomeTab = .macs @ViewBuilder var content: Content var body: some View { @@ -108,6 +110,9 @@ struct PushedScreenStandIn: View { content .fixedSize(horizontal: false, vertical: true) Spacer(minLength: 0) + TabBarStandIn(selected: tab, badge: 0) + .padding(.horizontal, 24) + .padding(.bottom, 28) } .frame(minHeight: 852, alignment: .top) } diff --git a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift index 25ea449d..4f1431d0 100644 --- a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift +++ b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift @@ -225,6 +225,15 @@ final class ScreenRenderTests: XCTestCase { requests([Self.card(Self.stagingDisplay, macName: "Office Mac", decision: .deny, secondsLeft: 236), Self.card(secondsLeft: 272)], biometry: .touchID)) try render("54-requests-empty-one-mac", requests([], approvingMacs: 1)) + // An accessibility text size, with a requester name as long as an agent may choose. + let longRequester = RequestDisplay( + requesterName: "Background Maintenance Agent for the Release Pipeline", purpose: "", + credentialName: "Production Database", commandLine: "psql", workingDirectory: "", executableName: "psql", + deliveryRows: []) + try render("57-requests-accessibility-size", + requests([Self.card(longRequester, secondsLeft: 48), + Self.card(decision: .allowOnce, isSent: true, secondsLeft: 236)]) + .environment(\.dynamicTypeSize, .accessibility2)) } func testHistoryTab() throws { From 83adfc2089c58b7044c12b3bea83f8c41846decd Mon Sep 17 00:00:00 2001 From: sudoHG Date: Mon, 16 Nov 2026 11:07:35 +0800 Subject: [PATCH 4/4] Say Macs can't reach the iPhone only while an iCloud banner shows (#346) With only notifications off, requests still arrive and the banner says what is wrong, so the empty state's capsule keeps counting the Macs. The orange form now follows the iCloud banners alone, as the maintainer decided from the renders; the capsule stays hidden without an approving Mac. Render 58 shows the green capsule under the notifications-off banner. --- iOS/AskKeyiOSKit/Views/RequestsView.swift | 39 +++++++++++-------- iOS/AskKeyiOSKitTests/HomeTests.swift | 16 ++++++-- iOS/AskKeyiOSKitTests/ScreenRenderTests.swift | 2 + 3 files changed, 37 insertions(+), 20 deletions(-) diff --git a/iOS/AskKeyiOSKit/Views/RequestsView.swift b/iOS/AskKeyiOSKit/Views/RequestsView.swift index 82dac90a..a22a7395 100644 --- a/iOS/AskKeyiOSKit/Views/RequestsView.swift +++ b/iOS/AskKeyiOSKit/Views/RequestsView.swift @@ -84,12 +84,9 @@ struct RequestsContent: View { if cards.isEmpty { Spacer(minLength: 24) if hasMacs { - let cannotReach = Self.macsCannotReach(accountNotice: accountNotice, notificationsOff: notificationsOff) EmptyStateView(symbol: "tray", title: "request.empty.title", detail: "request.empty.detail") { - // Without an approving Mac the Macs tab says why; the - // capsule has nothing true to count. - if cannotReach || approvingMacs > 0 { - ReachabilityCapsule(approvingMacs: approvingMacs, cannotReach: cannotReach) + if let capsule = Self.capsule(accountNotice: accountNotice, approvingMacs: approvingMacs) { + ReachabilityCapsule(state: capsule) } } } else { @@ -114,10 +111,14 @@ struct RequestsContent: View { .padding(.bottom, 24) } - /// While a banner shows, the Macs cannot reach this iPhone, or cannot - /// get the person's attention, so the empty state says so. - static func macsCannotReach(accountNotice: AccountNotice?, notificationsOff: Bool) -> Bool { - accountNotice != nil || notificationsOff + /// What the empty state's capsule says. While an iCloud banner shows, + /// the Macs cannot reach this iPhone. With notifications off, requests + /// still arrive and the banner says what is wrong, so the capsule still + /// counts the Macs. Without an approving Mac it is hidden: the Macs tab + /// says why, and there is nothing true to count. + static func capsule(accountNotice: AccountNotice?, approvingMacs: Int) -> ReachabilityCapsule.Reachability? { + if accountNotice != nil { return .unreachable } + return approvingMacs > 0 ? .reachable(approvingMacs) : nil } static func explanation(_ notice: AccountNotice) -> LocalizedStringKey { @@ -218,15 +219,19 @@ struct RequestRow: View { } /// Under the empty state: a green dot and how many Macs can send requests -/// here, or an orange dot while a banner says why they cannot. +/// here, or an orange dot while an iCloud banner says why they cannot. struct ReachabilityCapsule: View { - let approvingMacs: Int - let cannotReach: Bool + enum Reachability: Equatable { + case reachable(Int) + case unreachable + } + + let state: Reachability var body: some View { HStack(spacing: 8) { Circle() - .fill(cannotReach ? Color.orange : Color.green) + .fill(state == .unreachable ? Color.orange : Color.green) .frame(width: 8, height: 8) .accessibilityHidden(true) text @@ -242,8 +247,10 @@ struct ReachabilityCapsule: View { } private var text: Text { - if cannotReach { return Text("request.empty.unreachable", bundle: .kit) } - if approvingMacs == 1 { return Text("request.empty.reachableOne", bundle: .kit) } - return Text("request.empty.reachable \(String(approvingMacs))", bundle: .kit) + switch state { + case .unreachable: return Text("request.empty.unreachable", bundle: .kit) + case .reachable(1): return Text("request.empty.reachableOne", bundle: .kit) + case .reachable(let count): return Text("request.empty.reachable \(String(count))", bundle: .kit) + } } } diff --git a/iOS/AskKeyiOSKitTests/HomeTests.swift b/iOS/AskKeyiOSKitTests/HomeTests.swift index 25d2dcb6..6079a5c7 100644 --- a/iOS/AskKeyiOSKitTests/HomeTests.swift +++ b/iOS/AskKeyiOSKitTests/HomeTests.swift @@ -180,12 +180,20 @@ final class HomeTests: XCTestCase { XCTAssertTrue(RequestRow.short(long).hasSuffix("…")) } - func testTheCapsuleFollowsTheBanners() { + func testTheTimeLeftIsSpokenAsADuration() { XCTAssertEqual(RequestRow.spoken(272, locale: Locale(identifier: "en")), "4 minutes, 32 seconds") - XCTAssertFalse(RequestsContent.macsCannotReach(accountNotice: nil, notificationsOff: false)) - XCTAssertTrue(RequestsContent.macsCannotReach(accountNotice: nil, notificationsOff: true)) + } + + /// Only an iCloud banner makes the capsule say the Macs cannot reach + /// this iPhone; notifications off leave it counting the Macs, and it is + /// hidden without an approving Mac. + func testTheCapsuleSaysUnreachableOnlyWhileAnICloudBannerShows() { + XCTAssertEqual(RequestsContent.capsule(accountNotice: nil, approvingMacs: 2), .reachable(2)) + XCTAssertEqual(RequestsContent.capsule(accountNotice: nil, approvingMacs: 1), .reachable(1)) + XCTAssertNil(RequestsContent.capsule(accountNotice: nil, approvingMacs: 0)) for notice in [AccountNotice.signedOut, .restricted, .unavailable] { - XCTAssertTrue(RequestsContent.macsCannotReach(accountNotice: notice, notificationsOff: false)) + XCTAssertEqual(RequestsContent.capsule(accountNotice: notice, approvingMacs: 2), .unreachable) + XCTAssertEqual(RequestsContent.capsule(accountNotice: notice, approvingMacs: 0), .unreachable) } } diff --git a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift index 4f1431d0..fe1b1f15 100644 --- a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift +++ b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift @@ -220,6 +220,8 @@ final class ScreenRenderTests: XCTestCase { try render("45-requests-empty", requests([])) try render("46-requests-not-paired", requests([], hasMacs: false)) try render("47-requests-both-banners", requests([], accountNotice: .signedOut, notificationsOff: true)) + // Requests still arrive with notifications off: the capsule stays green. + try render("58-requests-notifications-off", requests([], notificationsOff: true)) // A decision stored but not yet saved, the Touch ID footnote, and one Mac. try render("53-requests-sending-touch-id", requests([Self.card(Self.stagingDisplay, macName: "Office Mac", decision: .deny, secondsLeft: 236),