diff --git a/docs/features.md b/docs/features.md
index 3277a9e..b9142c0 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 76eb241..c09f2bb 100644
--- a/iOS/AskKeyiOSKit/App/AppModel+Macs.swift
+++ b/iOS/AskKeyiOSKit/App/AppModel+Macs.swift
@@ -90,3 +90,88 @@ 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. 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 && !$0.isChecking }.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()
+ }
+
+ /// 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.
+ 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 0f14529..b9745bc 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] = [:]
@@ -33,11 +38,22 @@ 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?
@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] = []
@@ -83,6 +99,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
@@ -140,6 +158,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,11 +182,13 @@ 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()
await refreshList()
await restoreApprovals(services)
+ storedRequestsRestored = true
}
// MARK: Welcome
@@ -260,6 +281,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 5678da4..694ed0a 100644
--- a/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift
+++ b/iOS/AskKeyiOSKit/App/AskKeyAppDelegate.swift
@@ -28,13 +28,21 @@ 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). Whatever the extension could verify, the
+ /// notification shows as it would in the background.
+ static let foregroundPresentation: UNNotificationPresentationOptions = [.banner, .list, .sound]
+
+ /// 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,
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 6e73a75..e00faf7 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": "%@ · found when Ask Key checked its inbox"
+ "value": "After pairing, a Mac sends its agents' requests here when you're away from it."
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
- "value": "%@ · 请旨检查收件箱时发现"
+ "value": "配对后,Mac 上 Agent 的请求会在你不在 Mac 前时发到这里。"
}
}
}
},
- "list.deliveries.push %@": {
+ "list.empty.title": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "%@ · arrived through a notification"
+ "value": "No Paired Macs Yet"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
- "value": "%@ · 通过通知送达"
+ "value": "还没有配对的 Mac"
}
}
}
},
- "list.deliveries.title": {
+ "list.footer": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Delivery Checks"
+ "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": "送达检查"
+ "value": "这些 Mac 上的 Agent 想用凭证、而你不在 Mac 前时,请求会发到这台 iPhone。"
}
}
}
},
- "list.empty": {
+ "list.iCloud.restricted": {
"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": "Restricted"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
- "value": "还没有配对的 Mac。请在 Mac 上打开请旨的“设置”,选择“设备”,再选择“配对设备”。"
+ "value": "受到限制"
+ }
+ }
+ }
+ },
+ "list.iCloud.signedIn": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Signed in"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "已登录"
+ }
+ }
+ }
+ },
+ "list.iCloud.signedOut": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Signed out"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "已退出登录"
+ }
+ }
+ }
+ },
+ "list.iCloud.unavailable": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Can't connect"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "无法连接"
+ }
+ }
+ }
+ },
+ "list.lastDeliveryCheck": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Last delivery check"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "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,70 @@
}
}
},
- "list.title": {
+ "list.thisIPhone": {
"extractionState": "manual",
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
- "value": "Paired Macs"
+ "value": "This iPhone"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
- "value": "已配对的 Mac"
+ "value": "这台 iPhone"
+ }
+ }
+ }
+ },
+ "list.version %@": {
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Version %@"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "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": "配对于"
}
}
}
@@ -1378,6 +1633,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 +1786,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 +2211,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 +2636,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 cab195e..54f39ee 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 f276ad7..d856aea 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 da7f7fe..045c1af 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) }
+ .accessibilityHint(text)
+ .buttonStyle(.bordered)
+ .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 0000000..fe28361
--- /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 02a4882..97597c5 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,110 @@ 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) {
+ 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: {
+ 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: {
+ // What removing does is #342's confirmation, word for word.
+ if removalFailed {
+ Text("list.notice.removalFailed", bundle: .kit).foregroundStyle(.orange)
+ }
}
- 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)
+ 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)
+ .font(.subheadline)
+ .foregroundStyle(row.isApprover ? Color.secondary : Color.orange)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
}
- Button(action: onRemove) { Text("list.remove", bundle: .kit) }
- .buttonStyle(ActionButtonStyle(kind: .destructive))
+ .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 0000000..436040b
--- /dev/null
+++ b/iOS/AskKeyiOSKit/Views/MacsView.swift
@@ -0,0 +1,263 @@
+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,
+ 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 })
+ }
+ .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 on screen, with its dialogs, closes first.
+ if opened != nil, model.selectedTab == .macs { 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?
+ /// 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?
+ 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, accountChecked: accountChecked,
+ 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
+/// 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)
+ .frame(minWidth: 44, minHeight: 44)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .padding(.vertical, -10)
+ .padding(.trailing, -10)
+ .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 accountChecked: Bool
+ let notificationsOn: 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: notificationsOn == false ? "bell.slash" : "bell") {
+ Text("list.notifications", bundle: .kit)
+ } value: {
+ 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)
+ 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 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)
+ 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 8a03645..0000000
--- 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 3a37958..e68d622 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 0000000..a22a739
--- /dev/null
+++ b/iOS/AskKeyiOSKit/Views/RequestsView.swift
@@ -0,0 +1,256 @@
+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 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
+
+ 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: 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)
+ .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 struct ArrivalWatch: Equatable {
+ let shown: Bool
+ let arrivals: Set
+ }
+
+ 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") {
+ if let capsule = Self.capsule(accountNotice: accountNotice, approvingMacs: approvingMacs) {
+ ReachabilityCapsule(state: capsule)
+ }
+ }
+ } 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)
+ }
+
+ /// 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 {
+ 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
+ @Environment(\.locale) private var locale
+
+ var body: some View {
+ Button(action: onOpen) {
+ HStack(spacing: 12) {
+ VStack(alignment: .leading, spacing: 6) {
+ sentence
+ .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())
+ .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:
+ 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)
+ .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)
+ }
+}
+
+/// Under the empty state: a green dot and how many Macs can send requests
+/// here, or an orange dot while an iCloud banner says why they cannot.
+struct ReachabilityCapsule: View {
+ enum Reachability: Equatable {
+ case reachable(Int)
+ case unreachable
+ }
+
+ let state: Reachability
+
+ var body: some View {
+ HStack(spacing: 8) {
+ Circle()
+ .fill(state == .unreachable ? 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 {
+ 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/AskKeyiOSKit/Views/RootView.swift b/iOS/AskKeyiOSKit/Views/RootView.swift
index 209b917..1803250 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 d0efcbc..e84faab 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 0000000..6079a5c
--- /dev/null
+++ b/iOS/AskKeyiOSKitTests/HomeTests.swift
@@ -0,0 +1,225 @@
+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])
+ }
+
+ /// 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])
+ 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)
+ }
+
+ /// 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()
+ 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)
+ }
+
+ /// 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
+ 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.
+ /// 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 testTheTimeLeftIsSpokenAsADuration() {
+ XCTAssertEqual(RequestRow.spoken(272, locale: Locale(identifier: "en")), "4 minutes, 32 seconds")
+ }
+
+ /// 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] {
+ XCTAssertEqual(RequestsContent.capsule(accountNotice: notice, approvingMacs: 2), .unreachable)
+ XCTAssertEqual(RequestsContent.capsule(accountNotice: notice, approvingMacs: 0), .unreachable)
+ }
+ }
+
+ 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 0000000..3b122c4
--- /dev/null
+++ b/iOS/AskKeyiOSKitTests/RenderChrome.swift
@@ -0,0 +1,119 @@
+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
+/// and the tab bar, which stays visible.
+struct PushedScreenStandIn: View {
+ var tab: HomeTab = .macs
+ @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)
+ 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 e4f40cd..fe1b1f1 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,108 @@ 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, 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: approvingMacs,
+ accountNotice: accountNotice, notificationsOff: notificationsOff, biometry: biometry,
+ 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))
+ // 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),
+ 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 {
+ 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,
+ notifications: NotificationAuthorization = .allowed,
+ lastCheck: Date? = ScreenRenderTests.now.addingTimeInterval(-60)) -> some View {
+ TabScreenStandIn(tab: .macs, showsAdd: true) {
+ MacsContent(rows: rows, listNotice: notice, accountNotice: accountNotice, notifications: notifications,
+ 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, 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 {
diff --git a/scripts/build-ios.sh b/scripts/build-ios.sh
index 6069355..3f5358f 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('\\(')