diff --git a/Sources/AskKeyAppKit/App/AppDelegate+Approval.swift b/Sources/AskKeyAppKit/App/AppDelegate+Approval.swift index d9690e0..f074179 100644 --- a/Sources/AskKeyAppKit/App/AppDelegate+Approval.swift +++ b/Sources/AskKeyAppKit/App/AppDelegate+Approval.swift @@ -211,7 +211,8 @@ extension AppDelegate { let groupAllowance = GroupTimedAllowancePresentation(snapshot: pending?.groupAllowanceSnapshot) let remote = pending.map { RemoteApprovalPanelState(requestID: $0.requestID, - status: DeviceServicesHost.coordinator?.remoteApprovals[$0.requestID]) + status: DeviceServicesHost.coordinator?.remoteApprovals[$0.requestID], + footer: DeviceServicesHost.coordinator?.remoteFooterHint(for: $0.requestID)) } let panel = Self.makeFrozenApprovalPanel( FrozenAgentApprovalPrompt( @@ -313,6 +314,7 @@ extension AppDelegate { let coordinator = DeviceServicesHost.coordinator let step = remote.step(requestEnded: requestEnded, screenUnlocked: screenUnlocked, expired: expired, now: Date(), status: coordinator?.remoteApprovals[remote.requestID], + footer: coordinator?.remoteFooterHint(for: remote.requestID), lastDecision: coordinator?.lastRemoteDecision, applying: coordinator?.isApplyingRemoteDecision(to: remote.requestID) == true) if step == .close { finish(nil) } diff --git a/Sources/AskKeyAppKit/App/FrozenAgentApprovalPrompt.swift b/Sources/AskKeyAppKit/App/FrozenAgentApprovalPrompt.swift index 63b45aa..a452447 100644 --- a/Sources/AskKeyAppKit/App/FrozenAgentApprovalPrompt.swift +++ b/Sources/AskKeyAppKit/App/FrozenAgentApprovalPrompt.swift @@ -278,18 +278,39 @@ struct FrozenAgentApprovalPrompt: View { } } + /// One moving number at a time: the send countdown while the request + /// waits for a paired iPhone, otherwise the expiry (ADR 0014 → Mac App). + /// A footer too long for one line, as the English "Also on iPhone" form + /// is, puts the text and "Esc to decide later" on a line each, so + /// neither breaks. VoiceOver reads it as one sentence and decides later + /// when it is activated; mouse and Esc work as before. private var footer: some View { - HStack(spacing: Theme.Spacing.xs) { - TimelineView(.periodic(from: .now, by: 1)) { context in - Text(appLocalizedFormat("Expires in %@", FrozenCountdown.format(deadline: expiresAt, now: context.date))) - .monospacedDigit() + let hint = remote?.footer + return TimelineView(RemoteApprovalFooterSchedule(anchor: RemoteApprovalFooter.anchor(hint, expiresAt: expiresAt))) { context in + let text = RemoteApprovalFooter.text(hint, expiresAt: expiresAt, now: context.date) + ViewThatFits(in: .horizontal) { + HStack(spacing: Theme.Spacing.xs) { + Text(text).monospacedDigit() + Text(verbatim: "·") + decideLaterButton + } + VStack(spacing: Theme.Spacing.xs) { + Text(text).monospacedDigit() + decideLaterButton + } } - Text(verbatim: "·") - Button(appLocalized("Esc to decide later")) { finish(nil) } - .buttonStyle(.plain) - .keyboardShortcut(.cancelAction) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(verbatim: RemoteApprovalFooter.sentence(text))) + .accessibilityAddTraits(.isButton) + .accessibilityAction { finish(nil) } } .font(Theme.Fonts.caption) .foregroundStyle(Theme.textTertiary) } + + private var decideLaterButton: some View { + Button(appLocalized("Esc to decide later")) { finish(nil) } + .buttonStyle(.plain) + .keyboardShortcut(.cancelAction) + } } diff --git a/Sources/AskKeyAppKit/App/RemoteApprovalPanelState.swift b/Sources/AskKeyAppKit/App/RemoteApprovalPanelState.swift index d658086..ad93749 100644 --- a/Sources/AskKeyAppKit/App/RemoteApprovalPanelState.swift +++ b/Sources/AskKeyAppKit/App/RemoteApprovalPanelState.swift @@ -1,10 +1,84 @@ import Foundation import Observation +import SwiftUI + +/// What the approval panel's footer says about the approvers (ADR 0014 → +/// Mac App, amended by #345). Without a hint the footer is unchanged. +enum RemoteApprovalFooterHint: Equatable { + /// An eligible request waits for its 20-second send to an approver with + /// room under its limit. + case waiting(sendAt: Date) + /// A copy saved to an approver's inbox is still outstanding. + case sent +} + +/// The footer's text before "Esc to decide later": one moving number at a +/// time (#344, decision 6). The send countdown takes the expiry's place +/// while the request waits; the expiry returns once a copy was saved. +enum RemoteApprovalFooter { + static func text(_ hint: RemoteApprovalFooterHint?, expiresAt: Date?, now: Date) -> String { + let expiry = FrozenCountdown.format(deadline: expiresAt, now: now) + switch hint { + case .waiting(let sendAt): + guard let seconds = secondsUntilSend(sendAt, now: now) else { break } + // "s" inflects in neither catalog language; the count still goes + // through the plural lookup, so a language that inflects can add + // plural variations to this key. + return AppLanguage.localizedCount("iPhone can decide in %lld s", oneKey: "iPhone can decide in %lld s", + count: seconds, language: AppLanguage.current) + case .sent: + return appLocalizedFormat("Also on iPhone · Expires in %@", expiry) + case nil: + break + } + return appLocalizedFormat("Expires in %@", expiry) + } + + /// The whole footer as one sentence, for VoiceOver: the text, then + /// "Esc to decide later". + static func sentence(_ text: String) -> String { + text + " · " + appLocalized("Esc to decide later") + } + + /// Whole seconds left before the send, rounded up, from 20 to 1; nil + /// once the send is due, when the footer is unchanged until it is saved. + static func secondsUntilSend(_ sendAt: Date, now: Date) -> Int? { + let remaining = sendAt.timeIntervalSince(now) + guard remaining > 0 else { return nil } + return min(Int(remaining.rounded(.up)), Int(DeviceCoordinator.remoteSendDelay)) + } + + /// The moment the footer's number counts toward. + static func anchor(_ hint: RemoteApprovalFooterHint?, expiresAt: Date?) -> Date? { + if case .waiting(let sendAt) = hint { return sendAt } + return expiresAt + } +} + +/// Ticks once a second, just after each whole second before `anchor`, so +/// the footer's number changes when it should and not up to a second late. +struct RemoteApprovalFooterSchedule: TimelineSchedule { + /// How long after a whole second each tick falls, so rounding the + /// remaining time never lands on the boundary itself. + static let offset: TimeInterval = 0.01 + let anchor: Date? + + /// The first entry is the latest tick at or before `startDate`. + func entries(from startDate: Date, mode: TimelineScheduleMode) -> AnyIterator { + let base = (anchor ?? startDate).addingTimeInterval(Self.offset) + var step = startDate.timeIntervalSince(base).rounded(.down) + return AnyIterator { + defer { step += 1 } + return base.addingTimeInterval(step) + } + } +} /// What the open approval panel shows about a paired iPhone (ADR 0014 → Mac -/// App): where its request went, for Details, and the approver's decision -/// once it applied. The panel's privacy check feeds it the coordinator's -/// state on every tick and closes the panel when `step` says so. +/// App): where its request went, for Details, what the footer says about +/// the approvers, and the approver's decision once it applied. The panel's +/// privacy check feeds it the coordinator's state on every tick and closes +/// the panel when `step` says so. @Observable final class RemoteApprovalPanelState { /// How long "Approved on" or "Denied on" stays on an unlocked screen. @@ -22,21 +96,28 @@ final class RemoteApprovalPanelState { /// The approvers the request went to; kept after the request left /// pending, when the coordinator drops it. private(set) var status: RemoteApprovalStatus? + /// What the footer says about the approvers; nil once the request left + /// pending or an approver's decision was recorded. + private(set) var footer: RemoteApprovalFooterHint? /// The approver's decision that moved this request out of pending. private(set) var outcome: RemoteAppliedDecision? @ObservationIgnored private var outcomeShownAt: Date? @ObservationIgnored private var waitingSince: Date? - init(requestID: String, status: RemoteApprovalStatus? = nil) { + init(requestID: String, status: RemoteApprovalStatus? = nil, footer: RemoteApprovalFooterHint? = nil) { self.requestID = requestID self.status = status + self.footer = footer } /// Records the coordinator's latest decision when it decided this request. + /// The footer's hint goes with it, so "Also on iPhone" never shows next + /// to the approver's decision. func record(_ decision: RemoteAppliedDecision?, now: Date) { guard outcome == nil, let decision, decision.requestID == requestID else { return } outcome = decision outcomeShownAt = now + footer = nil } /// One privacy check. A locked screen closes the panel at once; an @@ -44,9 +125,12 @@ final class RemoteApprovalPanelState { /// any other way closes the panel, after at most `applyingGrace` while a /// decision for it is being applied. func step(requestEnded: Bool, screenUnlocked: Bool, expired: Bool, now: Date, - status: RemoteApprovalStatus?, lastDecision: RemoteAppliedDecision?, applying: Bool) -> Step { + status: RemoteApprovalStatus?, footer: RemoteApprovalFooterHint? = nil, + lastDecision: RemoteAppliedDecision?, applying: Bool) -> Step { if !requestEnded, status != self.status { self.status = status } record(lastDecision, now: now) + let footer = requestEnded || outcome != nil ? nil : footer + if footer != self.footer { self.footer = footer } guard screenUnlocked else { return .close } if let shownAt = outcomeShownAt { return now.timeIntervalSince(shownAt) >= Self.outcomeDuration ? .close : .keepOpen diff --git a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Presentation.swift b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Presentation.swift index 766e3d2..11c43ee 100644 --- a/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Presentation.swift +++ b/Sources/AskKeyAppKit/Devices/DeviceCoordinator+Presentation.swift @@ -15,4 +15,28 @@ extension DeviceCoordinator { func wasSentToApprover(_ requestID: String) -> Bool { remoteApprovals[requestID]?.approvers.contains { $0.sentAt != nil } == true } + + /// What the approval panel's footer says about the approvers (ADR 0014 → + /// Mac App, amended by #345), from the same state the sending follows: + /// `.waiting` while the request waits for its 20-second send with the + /// send time ahead, before its deadline, still eligible and with an + /// active approver below its outstanding limit; `.sent` while a copy + /// saved to an approver's inbox (Details' "Sent to") is undecided and + /// open; nil otherwise, including while sealing, while a first send + /// retries, when every approver is full and once every copy closed. + func remoteFooterHint(for requestID: String) -> RemoteApprovalFooterHint? { + guard let track = remoteRequests[requestID], track.ended == nil else { return nil } + switch track.phase { + case .waiting(let sendAt): + guard sendAt > now, let deadline = track.deadline, deadline > sendAt, remoteSendingAllowed, + activeApprovers(in: listedDevices).contains(where: { + outstandingCount(for: $0.device.deviceID) < Self.maximumOutstandingPerApprover + }) else { return nil } + return .waiting(sendAt: sendAt) + case .sent: + return track.entries.contains { $0.sentAt != nil && !$0.decided } ? .sent : nil + case .sending, .stayingOnMac: + return nil + } + } } diff --git a/Sources/AskKeyAppKit/Resources/Localizable.xcstrings b/Sources/AskKeyAppKit/Resources/Localizable.xcstrings index 608b593..35659c6 100644 --- a/Sources/AskKeyAppKit/Resources/Localizable.xcstrings +++ b/Sources/AskKeyAppKit/Resources/Localizable.xcstrings @@ -16041,6 +16041,52 @@ } } }, + "iPhone can decide in %lld s": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "iPhone can decide in %lld s" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "%lld 秒后 iPhone 也能处理" + } + }, + "qps-ploc": { + "stringUnit": { + "state": "translated", + "value": "[!!iPhone can decide in %lld s!!]" + } + } + } + }, + "Also on iPhone · Expires in %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Also on iPhone · Expires in %@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "iPhone 也能处理 · %@ 后失效" + } + }, + "qps-ploc": { + "stringUnit": { + "state": "translated", + "value": "[!!Also on iPhone · Expires in %@!!]" + } + } + } + }, "If verification fails, Ask Key restores the original settings.": { "extractionState": "extracted_with_value", "localizations": { diff --git a/Tests/AskKeyAppTests/RemoteApprovalFooterHintTests.swift b/Tests/AskKeyAppTests/RemoteApprovalFooterHintTests.swift new file mode 100644 index 0000000..2b70e84 --- /dev/null +++ b/Tests/AskKeyAppTests/RemoteApprovalFooterHintTests.swift @@ -0,0 +1,197 @@ +import AskKeyBroker +import AskKeyDevicesTestSupport +import AskKeyTestSupport +import Foundation +import XCTest +@testable import AskKeyAppKit +@testable import AskKeyDevices +@testable import AskKeyVault + +/// What the coordinator tells the approval panel's footer (ADR 0014 → Mac +/// App, amended by #345): the countdown only while an eligible request waits +/// for an approver with room, "Also on iPhone" only while a saved copy is +/// outstanding, and the unchanged footer in every other case. The footer +/// only reads; none of these steps changes what is sent. +@MainActor +final class RemoteApprovalFooterHintTests: AskKeyAppTestCase { + private var harness: DeviceCoordinatorHarness! + + override func setUp() async throws { + harness = try DeviceCoordinatorHarness() + await harness.coordinator.launch() + } + + override func tearDown() async throws { + try harness.close() + harness = nil + } + + private func hint(_ pending: BrokerPendingApproval) -> RemoteApprovalFooterHint? { + harness.coordinator.remoteFooterHint(for: pending.requestID) + } + + /// An unlocked Mac with an approver: a read waits for its 20-second send. + private func waitingRead() async throws -> (BrokerPendingApproval, Date) { + try await harness.pairApprover() + harness.script.screenUnlocked = true + let sendAt = harness.clock.now().addingTimeInterval(DeviceCoordinator.remoteSendDelay) + return (try harness.submitRead(), sendAt) + } + + private func passTheTwentySecondMark() async throws { + harness.clock.advance(by: DeviceCoordinator.remoteSendDelay) + await harness.coordinator.remoteApprovalTick() + } + + func testTheCountdownRunsUntilTheSendThenTheSavedCopySaysAlsoOnIPhone() async throws { + let (pending, sendAt) = try await waitingRead() + for _ in 0..<19 { + XCTAssertEqual(hint(pending), .waiting(sendAt: sendAt)) + harness.clock.advance(by: 1) + await harness.coordinator.remoteApprovalTick() + } + XCTAssertEqual(hint(pending), .waiting(sendAt: sendAt)) + harness.clock.advance(by: 1) + harness.coordinator.reconcileRemoteRequests() + XCTAssertEqual(harness.coordinator.remoteRequests[pending.requestID]?.phase, .sending) + XCTAssertNil(hint(pending), "unchanged while the request is being sealed") + try await harness.waitForRequests(1) + try await harness.waitUntil { harness.entries(pending).first?.sentAt != nil } + XCTAssertEqual(hint(pending), .sent) + XCTAssertTrue(harness.coordinator.wasSentToApprover(pending.requestID), "the same saved state as Details' Sent to") + } + + func testARequestDecidedOnTheMacWithinTwentySecondsNeverSaysAlsoOnIPhone() async throws { + let (pending, sendAt) = try await waitingRead() + harness.clock.advance(by: 10) + await harness.coordinator.remoteApprovalTick() + XCTAssertEqual(hint(pending), .waiting(sendAt: sendAt)) + _ = try harness.vault.decideAgentApproval(requestID: pending.requestID, capability: pending.capability, decision: .deny) + harness.coordinator.approvalRequestsChanged() + var seen: [RemoteApprovalFooterHint?] = [hint(pending)] + for _ in 0..<15 { + harness.clock.advance(by: 1) + await harness.coordinator.remoteApprovalTick() + seen.append(hint(pending)) + } + XCTAssertTrue(seen.allSatisfy { $0 == nil }) + XCTAssertTrue(harness.macSent(.approvalRequest).isEmpty) + } + + func testWithoutAnApproverTheFooterIsAlwaysUnchanged() async throws { + try await harness.pairPhone() + await harness.coordinator.removeDevice(harness.phone.deviceID) + try await harness.addUnflaggedEntry(for: harness.phone, name: "Synthetic Phone") + try harness.addCredential() + harness.script.screenUnlocked = true + let pending = try harness.submitRead() + for _ in 0..<25 { + XCTAssertNil(hint(pending)) + harness.clock.advance(by: 1) + await harness.coordinator.remoteApprovalTick() + } + XCTAssertNil(hint(pending)) + } + + func testRemovingTheLastApproverDuringTheWaitRestoresTheFooter() async throws { + let (pending, sendAt) = try await waitingRead() + XCTAssertEqual(hint(pending), .waiting(sendAt: sendAt)) + await harness.coordinator.removeDevice(harness.phone.deviceID) + XCTAssertNil(hint(pending)) + try await passTheTwentySecondMark() + XCTAssertNil(hint(pending)) + XCTAssertTrue(harness.macSent(.approvalRequest).isEmpty) + } + + func testAnUnavailableAccountDuringTheWaitRestoresTheFooter() async throws { + let (pending, sendAt) = try await waitingRead() + XCTAssertEqual(hint(pending), .waiting(sendAt: sendAt)) + harness.backend.accountState = .temporarilyUnavailable + await harness.coordinator.devicesOpened() + XCTAssertNotEqual(harness.coordinator.account, .available) + XCTAssertNil(hint(pending)) + } + + func testPausingAgentAccessDuringTheWaitRestoresTheFooter() async throws { + let (pending, sendAt) = try await waitingRead() + XCTAssertEqual(hint(pending), .waiting(sendAt: sendAt)) + try harness.vault.pauseAgentAccess(using: .allow) + XCTAssertNil(hint(pending)) + } + + func testARequestWhoseDeadlineComesBeforeItsSendNeverCountsDown() async throws { + let (pending, _) = try await waitingRead() + let deadline = try XCTUnwrap(pending.expiresAt) + harness.coordinator.remoteRequests[pending.requestID]?.phase = .waiting(sendAt: deadline.addingTimeInterval(1)) + XCTAssertNil(hint(pending), "a request that will not be sealed never promises the iPhone") + } + + func testWhenEveryApproverIsFullTheFooterIsUnchangedUntilOneHasRoom() async throws { + try await harness.pairApprover() + var sent: [BrokerPendingApproval] = [] + for _ in 0.. String { + RemoteApprovalFooter.sentence(RemoteApprovalFooter.text(hint, expiresAt: expiresAt, now: start.addingTimeInterval(seconds))) + } + + func testTheSendCountdownRunsFromTwentyToOneThenTheExpiryReturns() { + ApprovalCardFixtures.withLanguages { language in + let english = language == "en" + let waiting = RemoteApprovalFooterHint.waiting(sendAt: sendAt) + XCTAssertEqual(footer(waiting, at: 0), english + ? "iPhone can decide in 20 s · Esc to decide later" + : "20 秒后 iPhone 也能处理 · Esc 稍后处理") // i18n-literal: maintainer's Chinese footer (#344, decision 6). + for elapsed in 0..<20 { + // Each tick falls just after a whole second. + let seconds = 20 - elapsed + let expected = english ? "iPhone can decide in \(seconds) s" : "\(seconds) 秒后 iPhone 也能处理" // i18n-literal: Chinese countdown. + XCTAssertEqual(RemoteApprovalFooter.text(waiting, expiresAt: expiresAt, + now: start.addingTimeInterval(Double(elapsed) + 0.01)), expected) + XCTAssertEqual(RemoteApprovalFooter.text(waiting, expiresAt: expiresAt, + now: start.addingTimeInterval(Double(elapsed) + 0.99)), expected) + } + XCTAssertEqual(footer(waiting, at: 2), english + ? "iPhone can decide in 18 s · Esc to decide later" + : "18 秒后 iPhone 也能处理 · Esc 稍后处理") // i18n-literal: maintainer's Chinese footer (#344, decision 6). + XCTAssertEqual(footer(waiting, at: 19.5), english + ? "iPhone can decide in 1 s · Esc to decide later" + : "1 秒后 iPhone 也能处理 · Esc 稍后处理") // i18n-literal: Chinese footer at one second. + // The send is due but not saved yet: the footer is unchanged. + XCTAssertEqual(footer(waiting, at: 20), english + ? "Expires in 4:40 · Esc to decide later" : "4:40 后失效 · Esc 稍后处理") // i18n-literal: Chinese footer. + XCTAssertEqual(footer(.sent, at: 20.5), english + ? "Also on iPhone · Expires in 4:39 · Esc to decide later" + : "iPhone 也能处理 · 4:39 后失效 · Esc 稍后处理") // i18n-literal: maintainer's Chinese footer (#344, decision 6). + XCTAssertEqual(footer(nil, at: 0.5), english + ? "Expires in 4:59 · Esc to decide later" : "4:59 后失效 · Esc 稍后处理") // i18n-literal: Chinese footer. + } + } + + func testTheFooterNamesNoDeviceAndShowsNoSecondNumber() { + ApprovalCardFixtures.withLanguages { _ in + let waiting = RemoteApprovalFooter.text(.waiting(sendAt: sendAt), expiresAt: expiresAt, now: start) + XCTAssertFalse(waiting.contains(":"), "the expiry gives way to the send countdown: \(waiting)") + XCTAssertTrue(waiting.contains("iPhone")) + let sent = RemoteApprovalFooter.text(.sent, expiresAt: expiresAt, now: start) + XCTAssertTrue(sent.contains("5:00")) + XCTAssertTrue(sent.contains("iPhone")) + } + } + + func testTheScheduleTicksJustAfterEachWholeSecondOfTheAnchor() { + let schedule = RemoteApprovalFooterSchedule(anchor: sendAt) + let entries = schedule.entries(from: start.addingTimeInterval(2.5), mode: .normal) + let first = Array(entries.prefix(3)).map { $0.timeIntervalSince(start) } + XCTAssertEqual(first.count, 3) + for (index, offset) in first.enumerated() { + XCTAssertEqual(offset, 2.01 + Double(index), accuracy: 0.000_1) + } + ApprovalCardFixtures.withLanguages { language in + let texts = schedule.entries(from: start.addingTimeInterval(2.5), mode: .normal).prefix(3).map { + RemoteApprovalFooter.text(.waiting(sendAt: sendAt), expiresAt: expiresAt, now: $0) + } + XCTAssertEqual(texts, language == "en" + ? ["iPhone can decide in 18 s", "iPhone can decide in 17 s", "iPhone can decide in 16 s"] + : ["18 秒后 iPhone 也能处理", "17 秒后 iPhone 也能处理", "16 秒后 iPhone 也能处理"]) // i18n-literal: Chinese countdown. + } + let expiry = RemoteApprovalFooterSchedule(anchor: expiresAt).entries(from: start.addingTimeInterval(0.5), mode: .normal) + XCTAssertEqual(try XCTUnwrap(expiry.next()).timeIntervalSince(start), 0.01, accuracy: 0.000_1) + XCTAssertEqual(RemoteApprovalFooter.anchor(.waiting(sendAt: sendAt), expiresAt: expiresAt), sendAt) + XCTAssertEqual(RemoteApprovalFooter.anchor(.sent, expiresAt: expiresAt), expiresAt) + XCTAssertEqual(RemoteApprovalFooter.anchor(nil, expiresAt: expiresAt), expiresAt) + } + + func testThePanelStateFollowsTheCoordinatorUntilTheRequestEnds() { + let state = RemoteApprovalPanelState(requestID: "request", footer: .waiting(sendAt: sendAt)) + XCTAssertEqual(state.footer, .waiting(sendAt: sendAt)) + func step(ended: Bool = false, unlocked: Bool = true, footer: RemoteApprovalFooterHint?) -> RemoteApprovalPanelState.Step { + state.step(requestEnded: ended, screenUnlocked: unlocked, expired: false, now: start, status: nil, + footer: footer, lastDecision: nil, applying: false) + } + XCTAssertEqual(step(footer: nil), .keepOpen) + XCTAssertNil(state.footer, "a request that stopped being eligible shows the unchanged footer") + XCTAssertEqual(step(footer: .sent), .keepOpen) + XCTAssertEqual(state.footer, .sent) + XCTAssertEqual(step(ended: true, footer: .sent), .close) + XCTAssertNil(state.footer, "a request that left pending never says the iPhone can decide") + XCTAssertEqual(step(unlocked: false, footer: .sent), .close, "a lock closes the panel as before") + } + func testAnApproversDecisionClearsTheHintAtOnce() { + let state = RemoteApprovalPanelState(requestID: "request", footer: .sent) + state.record(RemoteAppliedDecision(requestID: "request", deviceName: "Synthetic iPhone", approved: true), now: start) + XCTAssertNil(state.footer, "\"Also on iPhone\" never shows next to \"Approved on\"") + XCTAssertEqual(state.step(requestEnded: false, screenUnlocked: true, expired: false, now: start, status: nil, + footer: .sent, lastDecision: nil, applying: true), .keepOpen) + XCTAssertNil(state.footer) + } + + /// The panel follows its state's hint, and a footer that needs a second + /// line, as the English sent form does, grows the panel downward: its top + /// edge, and with it every button, stays where it was. + func testTheFooterFollowsTheHintAndAGrowingFooterKeepsTheButtonsInPlace() throws { + _ = NSApplication.shared + try ApprovalCardFixtures.withLanguages { language in + let request = ApprovalCardFixtures.request(.read, display: ApprovalCardFixtures.display()) + let remote = RemoteApprovalPanelState(requestID: "synthetic", footer: .waiting(sendAt: Date(timeIntervalSinceNow: 18))) + let prompt = FrozenAgentApprovalPrompt(request: request, trustedCredentialName: "Staging API", + expiresAt: Date(timeIntervalSinceNow: 300), timedAllowanceEnabled: true, remote: remote, + finish: { _ in XCTFail("Laying out must never decide") }) + let panel = AppDelegate.makeFrozenApprovalPanel(prompt, visibleFrame: { _ in NSRect(x: 0, y: 0, width: 1440, height: 900) }) + defer { panel.contentViewController = nil; panel.close() } + func show(_ hint: RemoteApprovalFooterHint?) -> NSRect { + _ = remote.step(requestEnded: false, screenUnlocked: true, expired: false, now: Date(), status: nil, + footer: hint, lastDecision: nil, applying: false) + for _ in 0..<12 { + panel.layoutIfNeeded() + panel.contentView?.layoutSubtreeIfNeeded() + RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.02)) + } + return panel.frame + } + let waiting = show(.waiting(sendAt: Date(timeIntervalSinceNow: 18))) + let sent = show(.sent) + XCTAssertFalse(panel.isVisible) + XCTAssertEqual(sent.maxY, waiting.maxY, accuracy: 0.5, "the top edge stays") + if language == "en" { + XCTAssertGreaterThan(sent.height, waiting.height, "the English sent form takes a second line") + } else { + XCTAssertEqual(sent.height, waiting.height, accuracy: 0.5, "every Chinese form fits on one line") + } + XCTAssertEqual(show(nil), waiting, "the unchanged footer is one line again") + } + } +} diff --git a/Tests/AskKeyAppTests/RemoteApprovalRenderTests.swift b/Tests/AskKeyAppTests/RemoteApprovalRenderTests.swift index 76396ec..d09976d 100644 --- a/Tests/AskKeyAppTests/RemoteApprovalRenderTests.swift +++ b/Tests/AskKeyAppTests/RemoteApprovalRenderTests.swift @@ -14,7 +14,8 @@ import XCTest /// without approval, and Remove's confirmation; every step of the pairing /// sheet with its approval statements at its own size (a SwiftUI sheet can't /// be captured offscreen); and the approval panel through the production -/// panel factory. No window is ordered in. Set +/// panel factory, with its footer before and after the send (#350). No +/// window is ordered in. Set /// `REMOTE_APPROVAL_RENDER_DIRECTORY` to keep the PNGs, and also /// `REMOTE_APPROVAL_WINDOW_RENDERS=1` on a desktop session to render the /// Devices section in the real Settings window, scrolled to it. @@ -73,10 +74,11 @@ final class RemoteApprovalRenderTests: AskKeyAppTestCase { names += try await renderDevices(harness, language: language, tag: tag) names += try renderPanel(tag: tag) names += try renderPendingList(harness, language: language, tag: tag) + names += try renderFooters(tag: tag) } let files = try FileManager.default.contentsOfDirectory(atPath: directory.path).filter { $0.hasSuffix(".png") } XCTAssertEqual(Set(files), Set(names.map { $0 + ".png" })) - XCTAssertEqual(names.count, rendersWindow ? 32 : 30) + XCTAssertEqual(names.count, rendersWindow ? 38 : 36) } // MARK: Settings → Devices @@ -208,7 +210,6 @@ final class RemoteApprovalRenderTests: AskKeyAppTestCase { /// Details with where the request went, and an approver's decision, in /// the production panel. The card's front is the same as without them. private func renderPanel(tag: String) throws -> [String] { - let request = ApprovalCardFixtures.request(.read, display: ApprovalCardFixtures.display()) let sent = Date() let deviceID = try XCTUnwrap(DeviceID(rawValue: Data(repeating: 9, count: 16))) func status(delivered: Bool) -> RemoteApprovalStatus { @@ -216,8 +217,9 @@ final class RemoteApprovalRenderTests: AskKeyAppTestCase { deliveredAt: delivered ? sent.addingTimeInterval(2) : nil)]) } let cases: [(String, RemoteApprovalPanelState, Bool)] = [ - ("11", RemoteApprovalPanelState(requestID: "synthetic", status: status(delivered: false)), true), - ("12", RemoteApprovalPanelState(requestID: "synthetic", status: status(delivered: true)), true), + // Saved and still open, so the footer says "Also on iPhone" (#350). + ("11", RemoteApprovalPanelState(requestID: "synthetic", status: status(delivered: false), footer: .sent), true), + ("12", RemoteApprovalPanelState(requestID: "synthetic", status: status(delivered: true), footer: .sent), true), ("13", outcome(approved: true, status: status(delivered: true)), false), ("14", outcome(approved: false, status: status(delivered: true)), false), ] @@ -225,29 +227,78 @@ final class RemoteApprovalRenderTests: AskKeyAppTestCase { "13": "panel-approved-on-iphone", "14": "panel-denied-on-iphone"] var names: [String] = [] for (number, remote, expanded) in cases { - let prompt = FrozenAgentApprovalPrompt(request: request, trustedCredentialName: "Staging API", - expiresAt: Date(timeIntervalSinceNow: 300), timedAllowanceEnabled: true, remote: remote, - detailsExpanded: expanded, finish: { _ in XCTFail("Rendering must never decide") }) - let plain = FrozenAgentApprovalPrompt(request: request, trustedCredentialName: "Staging API", - expiresAt: nil, timedAllowanceEnabled: true, finish: { _ in }) - XCTAssertEqual(prompt.presentation.content, plain.presentation.content, "the card's front is unchanged") - XCTAssertEqual(prompt.presentation.buttons.map(\.identifier), plain.presentation.buttons.map(\.identifier)) - let panel = AppDelegate.makeFrozenApprovalPanel(prompt, visibleFrame: { _ in NSRect(x: 0, y: 0, width: 1440, height: 900) }) - panel.appearance = NSAppearance(named: .aqua) - defer { panel.contentViewController = nil; panel.close() } - let content = try XCTUnwrap(panel.contentView) - settle(panel) - XCTAssertFalse(panel.isVisible) - let frame = try XCTUnwrap(content.superview) - _ = try Self.render(frame) // warm lazy image drawing - RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.02)) let name = "\(number)-\(tag)-\(labels[number]!)" - try export(frame, as: name) + try renderPanel(remote: remote, expanded: expanded, expiresAt: Date(timeIntervalSinceNow: 300), as: name) names.append(name) } return names } + /// The footer with a paired iPhone (#350): the send countdown at 18 + /// seconds, "Also on iPhone" after the send, and the unchanged footer + /// when no approver can take the request. Details stay collapsed, so the + /// render shows the whole front next to the footer. + private func renderFooters(tag: String) throws -> [String] { + let deviceID = try XCTUnwrap(DeviceID(rawValue: Data(repeating: 9, count: 16))) + let sent = RemoteApprovalStatus(approvers: [.init(deviceID: deviceID, displayName: "Synthetic iPhone", + sentAt: Date(), deliveredAt: nil)]) + var names: [String] = [] + // The footer ticks just after each whole second before its anchor, so + // an anchor 0.05 s short of a whole second keeps the number for almost + // a second, longer than a render takes. + // A render that took longer is taken again, so the PNG shows `number`. + func footer(_ label: String, expiresIn: TimeInterval, shows number: String, + state: (Date) -> RemoteApprovalPanelState) throws { + let name = "\(label.prefix(2))-\(tag)-\(label.dropFirst(3))" + for _ in 0..<3 { + let now = Date() + let remote = state(now) + let expiresAt = now.addingTimeInterval(expiresIn) + let schedule = RemoteApprovalFooterSchedule(anchor: RemoteApprovalFooter.anchor(remote.footer, expiresAt: expiresAt)) + let tick = try XCTUnwrap(schedule.entries(from: now, mode: .normal).next()) + let shown = RemoteApprovalFooter.text(remote.footer, expiresAt: expiresAt, now: tick) + XCTAssertTrue(shown.contains(number), "\(label) shows \(shown)") + try renderPanel(remote: remote, expanded: false, expiresAt: expiresAt, as: name) + if Date().timeIntervalSince(now) < 0.9 { + names.append(name) + return + } + } + XCTFail("\(name) took longer than 0.9 s to render three times") + } + try footer("17-panel-footer-iphone-in-18s", expiresIn: 297.95, shows: "18") { + RemoteApprovalPanelState(requestID: "synthetic", footer: .waiting(sendAt: $0.addingTimeInterval(17.95))) + } + try footer("18-panel-footer-also-on-iphone", expiresIn: 279.95, shows: "4:39") { _ in + RemoteApprovalPanelState(requestID: "synthetic", status: sent, footer: .sent) + } + try footer("19-panel-footer-no-approver", expiresIn: 299.95, shows: "4:59") { _ in + RemoteApprovalPanelState(requestID: "synthetic") + } + return names + } + + private func renderPanel(remote: RemoteApprovalPanelState, expanded: Bool, expiresAt: Date, as name: String) throws { + let request = ApprovalCardFixtures.request(.read, display: ApprovalCardFixtures.display()) + let prompt = FrozenAgentApprovalPrompt(request: request, trustedCredentialName: "Staging API", + expiresAt: expiresAt, timedAllowanceEnabled: true, remote: remote, + detailsExpanded: expanded, finish: { _ in XCTFail("Rendering must never decide") }) + let plain = FrozenAgentApprovalPrompt(request: request, trustedCredentialName: "Staging API", + expiresAt: nil, timedAllowanceEnabled: true, finish: { _ in }) + XCTAssertEqual(prompt.presentation.content, plain.presentation.content, "the card's front is unchanged") + XCTAssertEqual(prompt.presentation.buttons.map(\.identifier), plain.presentation.buttons.map(\.identifier)) + let panel = AppDelegate.makeFrozenApprovalPanel(prompt, visibleFrame: { _ in NSRect(x: 0, y: 0, width: 1440, height: 900) }) + panel.appearance = NSAppearance(named: .aqua) + defer { panel.contentViewController = nil; panel.close() } + let content = try XCTUnwrap(panel.contentView) + settle(panel) + XCTAssertFalse(panel.isVisible) + let frame = try XCTUnwrap(content.superview) + _ = try Self.render(frame) // warm lazy image drawing + RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.02)) + try export(frame, as: name) + } + private func outcome(approved: Bool, status: RemoteApprovalStatus) -> RemoteApprovalPanelState { let state = RemoteApprovalPanelState(requestID: "synthetic", status: status) state.record(RemoteAppliedDecision(requestID: "synthetic", deviceName: "Synthetic iPhone", approved: approved), now: Date()) diff --git a/Tests/AskKeyE2ETests/ScreenshotE2ETests.swift b/Tests/AskKeyE2ETests/ScreenshotE2ETests.swift index ad574a5..ab65f6b 100644 --- a/Tests/AskKeyE2ETests/ScreenshotE2ETests.swift +++ b/Tests/AskKeyE2ETests/ScreenshotE2ETests.swift @@ -172,7 +172,8 @@ final class ScreenshotE2ETests: E2EBaseCase { XCTAssertEqual(app.buttons["approval-allow-once"].label, "Allow Once") XCTAssertEqual(app.buttons["approval-allow-timed"].label, "Allow for 30 Minutes") XCTAssertEqual(app.buttons["approval-deny"].label, "Deny") - waitForText("Esc to decide later") + // The footer is one VoiceOver sentence, "Expires in … · Esc to decide later" (#350). + waitForText("Esc to decide later", containing: true) XCTAssertFalse(app.staticTexts["Requested by"].exists, "everything else stays behind Details") capture("12-approval-default", approval: true) click("approval-details")