| 1 | import Foundation |
| 2 | import Testing |
| 3 | import EquipoShareCore |
| 4 | @testable import EquipoKit |
| 5 | |
| 6 | @MainActor @Suite struct NotificationDispatchTests { |
| 7 | static func encode<T: Encodable>(_ value: T) throws -> Data { |
| 8 | let encoder = EquipoJSON.encoder; encoder.dateEncodingStrategy = .iso8601 |
| 9 | return try encoder.encode(value) |
| 10 | } |
| 11 | static func setup() throws -> (NotificationDispatcher, EquipoSession, ScriptedTransport, URL, NotificationSelection) { |
| 12 | let server = ScriptedTransport() |
| 13 | let detail = try TaskDetailModelTests.model(server) |
| 14 | let selection = NotificationSelection(id: NotificationActionTests.binding, origin: server.origin, |
| 15 | person: detail.session.account.address!, credential: "fixture", sessionHash: nil) |
| 16 | let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| 17 | let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { .init(active: true, protectedData: true) }) |
| 18 | dispatcher.attach(session: detail.session, selection: selection) |
| 19 | server.on("GET /capabilities", .success(APIResponse(status: 200, data: Data(#"{"notification_actions_v1":true}"#.utf8)))) |
| 20 | var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 21 | var card = try #require(snapshot.cards?.first) |
| 22 | card.id = "card_1"; card.revision = 4; card.kind = "question"; card.state = "open"; card.options = []; card.question = "Which?" |
| 23 | snapshot.cards = [] // Bound card has aged out of the newest-50 snapshot. |
| 24 | server.on("GET /cards/card_1", .success(APIResponse(status: 200, data: try Self.encode(card)))) |
| 25 | server.on("GET /snapshot", .success(APIResponse(status: 200, data: try Self.encode(snapshot)))) |
| 26 | return (dispatcher, detail.session, server, directory, selection) |
| 27 | } |
| 28 | @Test func lostReplyRelaunchReusesBodyAndKeyFromDisk() async throws { |
| 29 | let (dispatcher, session, server, directory, selection) = try Self.setup() |
| 30 | defer { try? FileManager.default.removeItem(at: directory) } |
| 31 | server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| 32 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "my answer")) |
| 33 | await dispatcher.receive(response) |
| 34 | let first = try #require(server.sent("POST /cards/card_1/answer").first) |
| 35 | #expect(dispatcher.notices.first?.canRetry == true) |
| 36 | let restored = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { .init(active: true, protectedData: true) }) |
| 37 | restored.attach(session: session, selection: selection) |
| 38 | #expect(restored.notices.first?.canRetry == true) |
| 39 | #expect(server.sent("POST /cards/card_1/answer").count == 1, "restoration must not send automatically") |
| 40 | // Current card is no longer open: the original request must still reach |
| 41 | // the server's receipt lookup after a lost successful reply. |
| 42 | server.replace("GET /snapshot", with: .failure(EquipoAPIError.status(500))) |
| 43 | await restored.receive(response) |
| 44 | let requests = server.sent("POST /cards/card_1/answer") |
| 45 | try #require(requests.count == 2) |
| 46 | #expect(first.body == requests[1].body) |
| 47 | #expect(first.idempotencyKey == requests[1].idempotencyKey) |
| 48 | #expect(first.ifMatch == requests[1].ifMatch) |
| 49 | } |
| 50 | @Test func wrongBindingDisabledCapabilityAndStaleCardNeverWrite() async throws { |
| 51 | for mode in ["binding", "capability", "stale", "options", "ended", "placement", "by-name"] { |
| 52 | let (dispatcher, session, server, directory, _) = try Self.setup() |
| 53 | defer { try? FileManager.default.removeItem(at: directory) } |
| 54 | var changes: [String: Any] = [:] |
| 55 | if mode == "binding" { changes["binding_id"] = NotificationActionTests.notification } |
| 56 | if mode == "stale" { changes["card_revision"] = 3 } |
| 57 | if mode == "capability" { server.replace("GET /capabilities", with: .success(APIResponse(status: 200, data: Data("{}".utf8)))) } |
| 58 | if mode == "ended" { session.invalidate() } |
| 59 | if mode == "options" { |
| 60 | var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 61 | var card = try #require(snapshot.cards?.first) |
| 62 | card.id = "card_1"; card.revision = 4; card.kind = "question"; card.state = "open"; card.options = ["yes"] |
| 63 | snapshot.cards = [card] |
| 64 | server.replace("GET /cards/card_1", with: .success(APIResponse(status: 200, data: try Self.encode(card)))) |
| 65 | } |
| 66 | if mode == "placement" || mode == "by-name" { |
| 67 | let snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 68 | var card = try #require(snapshot.cards?.first) |
| 69 | card.id = "card_1"; card.revision = 4; card.kind = "question"; card.state = "open"; card.options = [] |
| 70 | var raw = try #require(JSONSerialization.jsonObject(with: Self.encode(card)) as? [String: Any]) |
| 71 | raw[mode == "placement" ? "placement_question" : "placement_by_name"] = true |
| 72 | server.replace("GET /cards/card_1", with: .success(APIResponse(status: 200, data: try JSONSerialization.data(withJSONObject: raw)))) |
| 73 | } |
| 74 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(changes), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| 75 | await dispatcher.receive(response) |
| 76 | #expect(server.requests.allSatisfy { $0.method == "GET" }) |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | @MainActor @Suite struct NotificationMergeTests { |
| 82 | @Test func mergeReadsFreshFactsAndOnlyPreparesConfirmation() async throws { |
| 83 | let server = TaskDetailServer(), detail = try TaskDetailModelTests.model(server) |
| 84 | await detail.load() |
| 85 | let task = try #require(detail.task) |
| 86 | var snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 87 | let card = try TaskDecisionTests.card(task) |
| 88 | snapshot.cards = [card] |
| 89 | let transport = NotificationMergeTransport(inner: server, snapshot: snapshot) |
| 90 | let session = try TaskDetailModelTests.model(transport).session |
| 91 | let selection = NotificationSelection(id: NotificationActionTests.binding, origin: transport.origin, person: session.account.address!, credential: "fixture", sessionHash: nil) |
| 92 | let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) |
| 93 | defer { try? FileManager.default.removeItem(at: directory) } |
| 94 | let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { .init(active: true, protectedData: true) }) |
| 95 | dispatcher.attach(session: session, selection: selection) |
| 96 | var payload = NotificationActionTests.payload(["card_kind": "merge", "card_revision": card.revision]) |
| 97 | var data = try #require(payload["equipo"] as? [String: Any]); data["card_id"] = card.id; data["task_id"] = task.id; payload["equipo"] = data |
| 98 | let response = try #require(NotificationResponse(userInfo: payload, category: "equipo.merge.v1", action: "merge", text: nil)) |
| 99 | await dispatcher.receive(response) |
| 100 | let context = try #require(dispatcher.notices.first?.context) |
| 101 | #expect(context.detail.confirmation?.card?.id == card.id) |
| 102 | #expect(context.detail.task?.candidateSha == task.candidateSha) |
| 103 | #expect(await server.writes == 0) |
| 104 | await server.answerSuccessfully(card) |
| 105 | await context.detail.confirm() |
| 106 | #expect(await server.writes == 1) |
| 107 | } |
| 108 | } |
| 109 | private struct NotificationMergeTransport: EquipoTransport { |
| 110 | let inner: TaskDetailServer |
| 111 | let snapshot: Snapshot |
| 112 | var origin: URL { inner.origin } |
| 113 | func send(_ request: APIRequest) async throws -> APIResponse { |
| 114 | if request.path == "/capabilities" { return APIResponse(status: 200, data: Data(#"{"notification_actions_v1":true}"#.utf8)) } |
| 115 | if request.method == "GET", request.path.hasPrefix("/cards/") { return try await APIResponse(status: 200, data: NotificationDispatchTests.encode(snapshot.cards!.first!)) } |
| 116 | if request.path == "/snapshot" { |
| 117 | var recent = snapshot; recent.cards = [] // The bound merge is outside the list window too. |
| 118 | return try await APIResponse(status: 200, data: NotificationDispatchTests.encode(recent)) |
| 119 | } |
| 120 | return try await inner.send(request) |
| 121 | } |
| 122 | func lines(_ request: APIRequest) async throws -> AsyncThrowingStream<String, Error> { try await inner.lines(request) } |
| 123 | } |
| 124 | |
| 125 | @MainActor @Suite struct NotificationLifecycleTests { |
| 126 | @Test func accountSwitchWhileReadingCannotSubmit() async throws { |
| 127 | let (_, session, server, directory, selection) = try NotificationDispatchTests.setup() |
| 128 | defer { try? FileManager.default.removeItem(at: directory) } |
| 129 | let gate = GatedTransport(inner: server, route: "GET /capabilities") |
| 130 | gate.hold = true |
| 131 | let gatedSession = try TaskDetailModelTests.model(gate).session |
| 132 | let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { .init(active: true, protectedData: true) }) |
| 133 | dispatcher.attach(session: gatedSession, selection: selection) |
| 134 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| 135 | let work = Task { await dispatcher.receive(response) } |
| 136 | await gate.waitUntilHeld() |
| 137 | dispatcher.attach(session: session, selection: NotificationSelection(id: NotificationActionTests.notification, origin: session.origin, person: session.account.address!, credential: "fixture", sessionHash: nil)) |
| 138 | gate.release(); await work.value |
| 139 | #expect(server.sent("POST /cards/card_1/answer").isEmpty) |
| 140 | #expect(dispatcher.notices.isEmpty) |
| 141 | } |
| 142 | @Test func signOutClearsPendingDiskAndNoTimerRetries() async throws { |
| 143 | let (dispatcher, _, server, directory, selection) = try NotificationDispatchTests.setup() |
| 144 | defer { try? FileManager.default.removeItem(at: directory) } |
| 145 | server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| 146 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| 147 | await dispatcher.receive(response) |
| 148 | let journal = ActionJournal(directory: directory) |
| 149 | #expect(try journal.load(id: response.binding.notificationId, binding: selection.id) != nil) |
| 150 | #expect(server.sent("POST /cards/card_1/answer").count == 1) |
| 151 | dispatcher.clear() |
| 152 | #expect(try journal.load(id: response.binding.notificationId, binding: selection.id) == nil) |
| 153 | #expect(dispatcher.notices.isEmpty) |
| 154 | } |
| 155 | @Test func staleResponseRefreshesAndShowsReviewedWords() async throws { |
| 156 | let (dispatcher, session, server, directory, selection) = try NotificationDispatchTests.setup() |
| 157 | defer { try? FileManager.default.removeItem(at: directory) } |
| 158 | let fixture: Snapshot = try Fixture.decode("thin/snapshot") |
| 159 | var updated = try #require(fixture.cards?.first) |
| 160 | updated.id = "card_1"; updated.revision = 5; updated.kind = "question"; updated.state = "open"; updated.question = "Changed question?" |
| 161 | server.on("GET /cards/card_1", .success(APIResponse(status: 200, data: try NotificationDispatchTests.encode(updated)))) |
| 162 | server.on("POST /cards/card_1/answer", .success(APIResponse(status: 409, data: Data(#"{"code":"card_stale","copy_key":"api.card_stale","request_id":"test"}"#.utf8)))) |
| 163 | var route: PushRoute? |
| 164 | dispatcher.onRoute = { route = $0 } |
| 165 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| 166 | await dispatcher.receive(response) |
| 167 | #expect(route == .card("card_1")) |
| 168 | #expect(dispatcher.notices.first?.error == EquipoStrings.text("api.card_stale")) |
| 169 | #expect(dispatcher.notices.first?.canRetry == false) |
| 170 | #expect(server.sent("GET /snapshot").count == 1) |
| 171 | #expect(server.sent("GET /cards/card_1").count == 2) |
| 172 | #expect(session.cards.first(where: { $0.id == "card_1" })?.revision == 5) |
| 173 | #expect(try ActionJournal(directory: directory).load(id: response.binding.notificationId, binding: selection.id) == nil) |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | @MainActor @Suite struct NotificationDuplicateTests { |
| 178 | @Test func doubleRetryCannotStartASecondInflightPost() async throws { |
| 179 | let (_, _, server, directory, selection) = try NotificationDispatchTests.setup() |
| 180 | defer { try? FileManager.default.removeItem(at: directory) } |
| 181 | let gate = GatedTransport(inner: server, route: "POST /cards/card_1/answer") |
| 182 | let session = try TaskDetailModelTests.model(gate).session |
| 183 | let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { .init(active: true, protectedData: true) }) |
| 184 | dispatcher.attach(session: session, selection: selection) |
| 185 | server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| 186 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| 187 | await dispatcher.receive(response) |
| 188 | let notice = try #require(dispatcher.notices.first) |
| 189 | try #require(server.sent("POST /cards/card_1/answer").count == 1) |
| 190 | gate.hold = true |
| 191 | let first = Task { await dispatcher.retry(notice) } |
| 192 | await gate.waitUntilHeld() |
| 193 | await dispatcher.retry(notice) |
| 194 | gate.release(); await first.value |
| 195 | #expect(server.sent("POST /cards/card_1/answer").count == 2) |
| 196 | } |
| 197 | @Test func changingDelegateBodyNeverReplacesEarlierPendingRequest() async throws { |
| 198 | let (dispatcher, _, server, directory, selection) = try NotificationDispatchTests.setup() |
| 199 | defer { try? FileManager.default.removeItem(at: directory) } |
| 200 | server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| 201 | let first = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "first")) |
| 202 | let changed = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "second")) |
| 203 | await dispatcher.receive(first) |
| 204 | let before = try ActionJournal(directory: directory).load(id: first.binding.notificationId, binding: selection.id) |
| 205 | await dispatcher.receive(changed) |
| 206 | #expect(server.sent("POST /cards/card_1/answer").count == 1) |
| 207 | #expect(dispatcher.notices.first?.error == EquipoStrings.text("api.idempotency_conflict")) |
| 208 | #expect(try ActionJournal(directory: directory).load(id: first.binding.notificationId, binding: selection.id) == before) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | @MainActor @Suite struct NotificationForegroundTests { |
| 213 | @Test func lockedOrInactiveBeforeOrAfterReadNeverJournalsOrPosts() async throws { |
| 214 | for mode in ["locked", "inactive", "locked-late", "inactive-late"] { |
| 215 | let (_, _, server, directory, selection) = try NotificationDispatchTests.setup() |
| 216 | defer { try? FileManager.default.removeItem(at: directory) } |
| 217 | let gate = GatedTransport(inner: server, route: "GET /cards/card_1") |
| 218 | gate.hold = mode.hasSuffix("late") |
| 219 | let session = try TaskDetailModelTests.model(gate).session |
| 220 | var state = NotificationAppState(active: true, protectedData: true) |
| 221 | if mode == "locked" { state.protectedData = false } |
| 222 | if mode == "inactive" { state.active = false } |
| 223 | let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { state }) |
| 224 | dispatcher.attach(session: session, selection: selection) |
| 225 | var route: PushRoute? |
| 226 | dispatcher.onRoute = { route = $0 } |
| 227 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| 228 | let job = Task { await dispatcher.receive(response) } |
| 229 | if mode.hasSuffix("late") { |
| 230 | await gate.waitUntilHeld() |
| 231 | if mode == "locked-late" { state.protectedData = false } else { state.active = false } |
| 232 | gate.release() |
| 233 | } |
| 234 | await job.value |
| 235 | #expect(server.sent("POST /cards/card_1/answer").isEmpty) |
| 236 | #expect(try ActionJournal(directory: directory).pending(binding: selection.id).isEmpty) |
| 237 | #expect(Self.files(directory).isEmpty, "a held reply never reaches disk") |
| 238 | #expect(route == .card("card_1")) |
| 239 | // Cold launch: the typed reply waits on its card, pre-filled, for one tap. |
| 240 | let notice = try #require(dispatcher.notices.first) |
| 241 | #expect(notice.held && notice.choice == "answer" && !notice.canRetry) |
| 242 | #expect(notice.card?.id == "card_1" && notice.card?.revision == 4) |
| 243 | state = NotificationAppState(active: true, protectedData: true) |
| 244 | await dispatcher.receive(response) |
| 245 | #expect(server.sent("POST /cards/card_1/answer").isEmpty, "redelivery never sends a held reply") |
| 246 | server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| 247 | notice.choice = "edited answer" |
| 248 | await dispatcher.answer(notice, choice: notice.choice) |
| 249 | let sent = try #require(server.sent("POST /cards/card_1/answer").first) |
| 250 | let raw = try #require(sent.body) |
| 251 | let body = try #require(JSONSerialization.jsonObject(with: raw) as? [String: Any]) |
| 252 | #expect(body["choice"] as? String == "edited answer") |
| 253 | #expect(!notice.held, "a confirmed reply is no longer held") |
| 254 | #expect(server.sent("POST /cards/card_1/answer").count == 1) |
| 255 | } |
| 256 | } |
| 257 | /// Every regular file under the journal directory. |
| 258 | static func files(_ directory: URL) -> [URL] { |
| 259 | let walk = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: [.isRegularFileKey]) |
| 260 | return (walk?.allObjects as? [URL] ?? []).filter { (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true } |
| 261 | } |
| 262 | static func choices(_ server: ScriptedTransport, _ route: String) throws -> [String] { |
| 263 | try server.sent(route).map { request in |
| 264 | let raw = try #require(request.body) |
| 265 | let body = try #require(JSONSerialization.jsonObject(with: raw) as? [String: Any]) |
| 266 | return try #require(body["choice"] as? String) |
| 267 | } |
| 268 | } |
| 269 | @Test func editedReplyThatFailsBeforeJournallingRetriesTheEdit() async throws { |
| 270 | let (_, session, server, directory, selection) = try NotificationDispatchTests.setup() |
| 271 | defer { try? FileManager.default.removeItem(at: directory) } |
| 272 | var state = NotificationAppState(active: false, protectedData: true) |
| 273 | let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { state }) |
| 274 | dispatcher.attach(session: session, selection: selection) |
| 275 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "original")) |
| 276 | await dispatcher.receive(response) |
| 277 | let notice = try #require(dispatcher.notices.first) |
| 278 | try #require(notice.held) |
| 279 | state = NotificationAppState(active: true, protectedData: true) |
| 280 | let card = try #require(notice.card) |
| 281 | server.replace("GET /cards/card_1", with: .failure(EquipoAPIError.offline)) |
| 282 | notice.choice = "edited" |
| 283 | await dispatcher.answer(notice, choice: notice.choice) |
| 284 | #expect(server.sent("POST /cards/card_1/answer").isEmpty) |
| 285 | #expect(notice.canRetry && !notice.uncertain && notice.card != nil, "nothing was journalled: the inputs stay usable") |
| 286 | #expect(Self.files(directory).isEmpty) |
| 287 | server.replace("GET /cards/card_1", with: .success(APIResponse(status: 200, data: try NotificationDispatchTests.encode(card)))) |
| 288 | server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| 289 | await dispatcher.retry(notice) |
| 290 | #expect(try Self.choices(server, "POST /cards/card_1/answer") == ["edited"]) |
| 291 | } |
| 292 | @Test func choicesFlowFreeTextRetriesWhatTheScreenShows() async throws { |
| 293 | let (dispatcher, _, server, directory, _) = try NotificationDispatchTests.setup() |
| 294 | defer { try? FileManager.default.removeItem(at: directory) } |
| 295 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.choices.v1", action: "answer", text: nil)) |
| 296 | await dispatcher.receive(response) |
| 297 | let notice = try #require(dispatcher.notices.first) |
| 298 | let card = try #require(notice.card) |
| 299 | try #require(card.options?.isEmpty != false) |
| 300 | server.replace("GET /capabilities", with: .failure(EquipoAPIError.offline)) |
| 301 | await dispatcher.answer(notice, choice: "typed") |
| 302 | #expect(server.sent("POST /cards/card_1/answer").isEmpty) |
| 303 | #expect(notice.canRetry && !notice.uncertain && notice.card != nil, "the card's inputs are re-enabled") |
| 304 | server.replace("GET /capabilities", with: .success(APIResponse(status: 200, data: Data(#"{"notification_actions_v1":true}"#.utf8)))) |
| 305 | server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| 306 | notice.choice = "typed again" |
| 307 | await dispatcher.retry(notice) |
| 308 | #expect(try Self.choices(server, "POST /cards/card_1/answer") == ["typed again"]) |
| 309 | #expect(notice.uncertain, "a journalled request locks the inputs") |
| 310 | await dispatcher.answer(notice, choice: "something else") |
| 311 | #expect(try Self.choices(server, "POST /cards/card_1/answer") == ["typed again"], "a locked card takes no new answer") |
| 312 | } |
| 313 | static func card() throws -> ThinCard { |
| 314 | let snapshot: Snapshot = try Fixture.decode("thin/snapshot") |
| 315 | var card = try #require(snapshot.cards?.first) |
| 316 | card.id = "card_1"; card.revision = 4; card.kind = "question"; card.state = "open"; card.options = []; card.question = "Which?" |
| 317 | return card |
| 318 | } |
| 319 | @Test func aNoticeFromAnotherBindingNeverWrites() async throws { |
| 320 | let (dispatcher, _, server, directory, selection) = try NotificationDispatchTests.setup() |
| 321 | defer { try? FileManager.default.removeItem(at: directory) } |
| 322 | server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| 323 | let other = "33333333-3333-4333-8333-333333333333" |
| 324 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(["binding_id": other]), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| 325 | let card = try Self.card() |
| 326 | let notice = NotificationNotice(response) |
| 327 | notice.canRetry = true |
| 328 | dispatcher.notices.append(notice) |
| 329 | await dispatcher.retry(notice) |
| 330 | notice.card = card; notice.choice = "answer"; notice.canRetry = false |
| 331 | await dispatcher.answer(notice, choice: "answer") |
| 332 | #expect(server.sent("POST /cards/card_1/answer").isEmpty) |
| 333 | #expect(server.sent("GET /cards/card_1").isEmpty) |
| 334 | #expect(try ActionJournal(directory: directory).pending(binding: selection.id).isEmpty) |
| 335 | #expect(Self.files(directory).isEmpty) |
| 336 | } |
| 337 | @Test func coldLaunchTryAgainWaitsForTheTap() async throws { |
| 338 | for state0 in [NotificationAppState(active: false, protectedData: true), NotificationAppState(active: true, protectedData: false)] { |
| 339 | let (_, session, server, directory, selection) = try NotificationDispatchTests.setup() |
| 340 | defer { try? FileManager.default.removeItem(at: directory) } |
| 341 | var state = state0 |
| 342 | let dispatcher = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { state }) |
| 343 | dispatcher.attach(session: session, selection: selection) |
| 344 | var route: PushRoute? |
| 345 | dispatcher.onRoute = { route = $0 } |
| 346 | let info: [AnyHashable: Any] = ["equipo": ["kind": "task", "task_id": "task_1", "actions": [ |
| 347 | "version": 1, "binding_id": NotificationActionTests.binding, "notification_id": NotificationActionTests.notification, |
| 348 | "task_revision": 3, "step_id": "step_1", "step_revision": 2, "attempt": 1]]] |
| 349 | let response = try #require(NotificationResponse(userInfo: info, category: "equipo.stopped.v1", action: "retry", text: nil)) |
| 350 | await dispatcher.receive(response) |
| 351 | #expect(server.sent("POST /tasks/task_1/retry").isEmpty) |
| 352 | #expect(Self.files(directory).isEmpty, "a held retry never reaches disk") |
| 353 | #expect(route == response.route) |
| 354 | let notice = try #require(dispatcher.notices.first) |
| 355 | #expect(notice.held && notice.canRetry) |
| 356 | state = NotificationAppState(active: true, protectedData: true) |
| 357 | await dispatcher.receive(response) |
| 358 | #expect(server.sent("POST /tasks/task_1/retry").isEmpty, "redelivery never sends a held retry") |
| 359 | server.on("POST /tasks/task_1/retry", .success(APIResponse(status: 202, data: Data(#"{"attempt":2}"#.utf8)))) |
| 360 | await dispatcher.retry(notice) |
| 361 | let sent = server.sent("POST /tasks/task_1/retry") |
| 362 | try #require(sent.count == 1) |
| 363 | let raw = try #require(sent[0].body) |
| 364 | let body = try #require(JSONSerialization.jsonObject(with: raw) as? [String: Any]) |
| 365 | #expect(body["step_id"] as? String == "step_1" && body["attempt"] as? Int == 1 && body["revision"] as? Int == 3) |
| 366 | #expect(dispatcher.notices.isEmpty) |
| 367 | } |
| 368 | } |
| 369 | @Test func restoredReplyNeverResendsWhileLockedOrInactive() async throws { |
| 370 | for state in [NotificationAppState(active: false, protectedData: true), NotificationAppState(active: true, protectedData: false)] { |
| 371 | let (dispatcher, session, server, directory, selection) = try NotificationDispatchTests.setup() |
| 372 | defer { try? FileManager.default.removeItem(at: directory) } |
| 373 | server.on("POST /cards/card_1/answer", .failure(EquipoAPIError.offline)) |
| 374 | let response = try #require(NotificationResponse(userInfo: NotificationActionTests.payload(), category: "equipo.question.text.v1", action: "answer", text: "answer")) |
| 375 | await dispatcher.receive(response) |
| 376 | try #require(server.sent("POST /cards/card_1/answer").count == 1) |
| 377 | let restored = NotificationDispatcher(journal: ActionJournal(directory: directory), appState: { state }) |
| 378 | restored.attach(session: session, selection: selection) |
| 379 | let notice = try #require(restored.notices.first) |
| 380 | await restored.retry(notice) |
| 381 | #expect(server.sent("POST /cards/card_1/answer").count == 1) |
| 382 | #expect(restored.notices.first === notice && notice.canRetry, "the pending reply stays on screen") |
| 383 | #expect(try ActionJournal(directory: directory).load(id: response.binding.notificationId, binding: selection.id) != nil, "the exact request stays for a foreground retry") |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | |