import Foundation import Testing import UserNotifications @testable import EquipoKit @MainActor @Suite struct NotificationActionTests { static let binding = "11111111-1111-1111-1111-111111111111" static let notification = "22222222-2222-2222-2222-222222222222" static func payload(_ changes: [String: Any] = [:]) -> [AnyHashable: Any] { var actions: [String: Any] = ["version": 1, "binding_id": binding, "notification_id": notification, "card_kind": "question", "card_revision": 4] for (key, value) in changes { actions[key] = value } return ["equipo": ["kind": "card", "card_id": "card_1", "task_id": "task_1", "actions": actions]] } @Test func onlyKnownCompleteBindingsCanAct() throws { let info = Self.payload() let answer = try #require(NotificationResponse(userInfo: info, category: "equipo.question.text.v1", action: "answer", text: "My answer")) #expect(answer.intent == .answer("My answer")) #expect(answer.binding.cardRevision == 4) for changes: [String: Any] in [["version": 2], ["version": true], ["card_revision": 0], ["card_revision": true], ["binding_id": "wrong"], ["notification_id": ""], ["card_kind": "merge"]] { #expect(NotificationResponse(userInfo: Self.payload(changes), category: "equipo.question.text.v1", action: "answer", text: "answer") == nil) } #expect(NotificationResponse(userInfo: info, category: "unknown", action: "answer", text: "answer") == nil) #expect(NotificationResponse(userInfo: info, category: "equipo.question.text.v1", action: "merge", text: nil) == nil) #expect(NotificationResponse(userInfo: info, category: "equipo.question.text.v1", action: "answer", text: nil) == nil) #expect(NotificationResponse(userInfo: info, category: "equipo.question.choices.v1", action: "answer", text: "ignored")?.intent == .question) } @Test func everyResponseRequiresUnlockAndForeground() { let categories = NotificationCategories.all #expect(categories.first(where: { $0.identifier == "needs_you" })?.actions.isEmpty == true) #expect(categories.count == 5) for category in categories where category.identifier != "needs_you" { #expect(!category.actions.isEmpty && category.actions.count <= 2) for action in category.actions { #expect(action.options.contains(.authenticationRequired)) #expect(action.options.contains(.foreground)) } } let text = categories.first { $0.identifier == "equipo.question.text.v1" } #expect(text?.actions.first is UNTextInputNotificationAction) let choices = categories.first { $0.identifier == "equipo.question.choices.v1" } #expect(!(choices?.actions.first is UNTextInputNotificationAction)) } @Test func receiptBodyKeepsOriginalKeyAndRevision() throws { let response = try #require(NotificationResponse(userInfo: Self.payload(), category: "equipo.question.text.v1", action: "answer", text: " My answer ")) let write = try response.pendingWrite() let body = try #require(JSONSerialization.jsonObject(with: write.body) as? [String: Any]) #expect(body["choice"] as? String == " My answer ") #expect(body["revision"] as? Int == 4) #expect(body["idempotency_key"] as? String == write.key) #expect(write.key == Self.notification) #expect(write.ifMatch == 4) let merge = try #require(NotificationResponse(userInfo: Self.payload(["card_kind": "merge"]), category: "equipo.merge.v1", action: "merge", text: nil)) #expect(throws: (any Error).self) { try merge.pendingWrite() } } } @MainActor @Suite struct NotificationBindingTests { @Test func stableOnRelaunchButRotatesAcrossSignIns() throws { let store = MemorySecretStore() let accounts = DeviceAccounts(store: store) var account = DeviceAccount.new(origin: URL(string: "https://equipo.test")!, label: "Phone") account.address = "person@example.test" account.credential = DeviceCredential(id: "device1", token: "secret", audience: "equipo", instanceId: "team", expiresAt: .distantFuture) try accounts.commit(.selectForNotifications(account), lifetime: accounts.lifetimes.current) let original = try #require(accounts.notificationSelection) try accounts.commit(.selectForNotifications(account), lifetime: accounts.lifetimes.current) #expect(accounts.notificationSelection == original) let restored = DeviceAccounts(store: store) try restored.commit(.selectForNotifications(account), lifetime: restored.lifetimes.current) #expect(restored.notificationSelection == original) account.credential = DeviceCredential(id: "device2", token: "new-secret", audience: "equipo", instanceId: "team", expiresAt: .distantFuture) try accounts.commit(.selectForNotifications(account), lifetime: accounts.lifetimes.current) #expect(accounts.notificationSelection?.id != original.id) try accounts.commit(.clearNotificationSelection(account), lifetime: accounts.lifetimes.current) #expect(accounts.notificationSelection == nil) try accounts.commit(.selectForNotifications(account), lifetime: accounts.lifetimes.current) let stale = accounts.lifetimes.current accounts.lifetimes.begin() #expect(throws: (any Error).self) { try accounts.commit(.clearNotificationSelection(account), lifetime: stale) } #expect(accounts.notificationSelection != nil) } @Test func registrationOptsInOnlyAfterCapability() async throws { for enabled in [false, true] { let transport = ScriptedTransport() transport.on("GET /capabilities", .success(APIResponse(status: 200, data: Data("{\"notification_actions_v1\":\(enabled)}".utf8)))) transport.on("POST /push-registrations", .success(APIResponse(status: 200, data: Data(#"{"environment":"production","platform":"macos","live_activities":false,"updated_at":"2026-11-27T10:00:00Z"}"#.utf8)))) let registrar = PushRegistrar(environment: .production, platform: .macos) await registrar.deviceTokenChanged(Data(repeating: 1, count: 32)) await registrar.attach(EquipoClient(transport: transport, token: "secret"), bindingID: NotificationActionTests.binding) let sent = try #require(transport.sent("POST /push-registrations").first) let raw = try #require(sent.body) let body = try #require(JSONSerialization.jsonObject(with: raw) as? [String: Any]) #expect((body["actions_version"] as? Int) == (enabled ? 1 : nil)) #expect((body["binding_id"] as? String) == (enabled ? NotificationActionTests.binding : nil)) } } } @MainActor @Suite struct NotificationRegistrationFallbackTests { @Test func forbiddenActionsRefreshCapabilitiesAndRegisterOpenOnly() async throws { let server = ScriptedTransport() server.on("GET /capabilities", .success(APIResponse(status: 200, data: Data(#"{"notification_actions_v1":true}"#.utf8)))) server.on("GET /capabilities", .success(APIResponse(status: 200, data: Data("{}".utf8)))) server.on("POST /push-registrations", .success(APIResponse(status: 403, data: Data(#"{"code":"forbidden"}"#.utf8)))) server.on("POST /push-registrations", .success(APIResponse(status: 200, data: Data(#"{"environment":"production","platform":"macos","live_activities":false,"updated_at":"2026-11-27T10:00:00Z"}"#.utf8)))) let registrar = PushRegistrar(environment: .production, platform: .macos) await registrar.deviceTokenChanged(Data(repeating: 1, count: 32)) await registrar.attach(EquipoClient(transport: server, token: "secret"), bindingID: NotificationActionTests.binding) #expect(server.sent("GET /capabilities").count == 2) let posts = server.sent("POST /push-registrations") try #require(posts.count == 2) let raw = try #require(posts[1].body) let body = try #require(JSONSerialization.jsonObject(with: raw) as? [String: Any]) #expect(body["actions_version"] == nil) #expect(body["binding_id"] == nil) await registrar.sync() #expect(server.sent("POST /push-registrations").count == 2) } }