| 1 | import Foundation |
| 2 | import Observation |
| 3 | import EquipoShareCore |
| 4 | #if os(iOS) |
| 5 | import UIKit |
| 6 | #elseif os(macOS) |
| 7 | import AppKit |
| 8 | #endif |
| 9 | |
| 10 | struct NotificationAppState { |
| 11 | var active: Bool |
| 12 | var protectedData: Bool |
| 13 | @MainActor static var current: Self { |
| 14 | #if os(iOS) |
| 15 | Self(active: UIApplication.shared.applicationState == .active, protectedData: UIApplication.shared.isProtectedDataAvailable) |
| 16 | #elseif os(macOS) |
| 17 | Self(active: NSApplication.shared.isActive, protectedData: true) |
| 18 | #else |
| 19 | Self(active: false, protectedData: false) |
| 20 | #endif |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | @MainActor @Observable final class NotificationNotice: Identifiable { |
| 25 | let response: NotificationResponse |
| 26 | nonisolated let id: String |
| 27 | var error: String? |
| 28 | var canRetry = false |
| 29 | var busy = false |
| 30 | var card: ThinCard? |
| 31 | var context: MacTaskContext? |
| 32 | var choice = "" |
| 33 | /// The person's action waits, in memory only, for their tap: it arrived |
| 34 | /// while the app was inactive or the device locked. |
| 35 | var held = false |
| 36 | /// A journalled request may have reached the server: Try again resends it |
| 37 | /// exactly as stored, so the card's inputs stay locked. |
| 38 | var uncertain = false |
| 39 | init(_ response: NotificationResponse) { self.response = response; id = response.binding.notificationId } |
| 40 | } |
| 41 | |
| 42 | /// Foreground responses only. A saved request is retried only on a response |
| 43 | /// delivery or the person's Retry tap, never by refresh or a background timer. |
| 44 | @MainActor @Observable final class NotificationDispatcher { |
| 45 | private let journal: ActionJournal |
| 46 | private var session: EquipoSession? |
| 47 | private var selection: NotificationSelection? |
| 48 | private var queued: [NotificationResponse] = [] |
| 49 | private var inFlight: Set<String> = [] |
| 50 | var notices: [NotificationNotice] = [] |
| 51 | var onRoute: ((PushRoute) -> Void)? |
| 52 | private struct Stored: Codable { let response: NotificationResponse; let write: PendingWrite } |
| 53 | private let appState: () -> NotificationAppState |
| 54 | init(journal: ActionJournal, appState: @escaping () -> NotificationAppState = { .current }) { |
| 55 | self.journal = journal; self.appState = appState |
| 56 | } |
| 57 | static func live() -> NotificationDispatcher { |
| 58 | let folder = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| 59 | .appendingPathComponent("Equipo/NotificationActions", isDirectory: true) |
| 60 | .appendingPathComponent(Bundle.main.bundleIdentifier ?? "unbundled", isDirectory: true) |
| 61 | return NotificationDispatcher(journal: ActionJournal(directory: folder)) |
| 62 | } |
| 63 | func attach(session: EquipoSession, selection: NotificationSelection?) { |
| 64 | let restoring = self.session !== session || self.selection != selection |
| 65 | if let old = self.selection, old != selection { clear() } |
| 66 | self.session = session; self.selection = selection |
| 67 | if restoring, let selection, current(session, selection), let records = try? journal.pending(binding: selection.id) { |
| 68 | for data in records { |
| 69 | guard let stored = try? JSONDecoder().decode(Stored.self, from: data), stored.response.binding.bindingId == selection.id, |
| 70 | !notices.contains(where: { $0.id == stored.response.binding.notificationId }) else { continue } |
| 71 | let notice = NotificationNotice(stored.response) |
| 72 | notice.canRetry = true; notice.error = EquipoStrings.text("native.share.unconfirmed") |
| 73 | notices.append(notice) |
| 74 | } |
| 75 | } |
| 76 | let pending = queued; queued = [] |
| 77 | for response in pending { Task { await receive(response) } } |
| 78 | } |
| 79 | func clear() { |
| 80 | session = nil; selection = nil; queued = []; notices = []; inFlight = [] |
| 81 | journal.clear() |
| 82 | } |
| 83 | private func current(_ session: EquipoSession, _ selection: NotificationSelection) -> Bool { |
| 84 | self.session === session && self.selection == selection && session.lifetime.isActive && !session.isInvalidated && selection.matches(session.account) |
| 85 | } |
| 86 | func dismiss(_ id: String) { notices.removeAll { $0.id == id } } |
| 87 | func receive(_ response: NotificationResponse) async { |
| 88 | guard let session, selection != nil else { |
| 89 | if queued.count < 32, !queued.contains(response) { queued.append(response) } |
| 90 | return |
| 91 | } |
| 92 | guard let selection, current(session, selection), response.binding.bindingId == selection.id else { return } |
| 93 | if response.intent == .open { onRoute?(response.taskID.map(PushRoute.task) ?? response.route); return } |
| 94 | guard !inFlight.contains(response.binding.notificationId) else { return } |
| 95 | let notice: NotificationNotice |
| 96 | if let existing = notices.first(where: { $0.id == response.binding.notificationId }) { |
| 97 | guard existing.response == response else { existing.error = EquipoStrings.text("api.idempotency_conflict"); return } |
| 98 | // A held action is sent only by the person's tap, never by a redelivery. |
| 99 | guard !existing.held else { return } |
| 100 | notice = existing |
| 101 | } else { notice = NotificationNotice(response); notices.append(notice) } |
| 102 | await run(notice, session: session, selection: selection) |
| 103 | } |
| 104 | func retry(_ notice: NotificationNotice) async { |
| 105 | guard notice.canRetry, let session, let selection, current(session, selection) else { return } |
| 106 | // A shown card with nothing journalled sends what the screen shows. |
| 107 | if notice.card != nil, !notice.uncertain { await answer(notice, choice: notice.choice); return } |
| 108 | await run(notice, session: session, selection: selection) |
| 109 | } |
| 110 | func answer(_ notice: NotificationNotice, choice: String) async { |
| 111 | guard !notice.busy, !notice.uncertain, let card = notice.card, let session, let selection, current(session, selection), |
| 112 | card.revision == notice.response.binding.cardRevision, card.isOpen, card.kind == "question", |
| 113 | (card.options?.isEmpty != false ? !choice.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty : card.options!.contains(choice)), |
| 114 | choice.utf8.count <= 16 * 1024 else { return } |
| 115 | notice.choice = choice |
| 116 | await run(notice, session: session, selection: selection, selectedChoice: choice) |
| 117 | } |
| 118 | /// Writes only while the device is unlocked and the app is active in the |
| 119 | /// foreground. Otherwise the action is held in memory on its notice, bound |
| 120 | /// to the card and revision it read: the typed answer pre-filled, or Try |
| 121 | /// again, for the person to confirm with one tap. Nothing reaches disk. |
| 122 | private func foreground(_ notice: NotificationNotice, card: ThinCard?) -> Bool { |
| 123 | let state = appState() |
| 124 | guard state.active && state.protectedData else { |
| 125 | if let card, card.revision == notice.response.binding.cardRevision { notice.card = card } |
| 126 | if case .answer(let text) = notice.response.intent, notice.choice.isEmpty { notice.choice = text } |
| 127 | if notice.response.intent == .retry { notice.canRetry = true } |
| 128 | notice.held = true |
| 129 | onRoute?(notice.response.route) |
| 130 | return false |
| 131 | } |
| 132 | return true |
| 133 | } |
| 134 | private func run(_ notice: NotificationNotice, session: EquipoSession, selection: NotificationSelection, selectedChoice: String? = nil) async { |
| 135 | let response = notice.response, id = notice.id |
| 136 | // The notice's own binding, not only the session's, must be the current one. |
| 137 | guard !inFlight.contains(id), current(session, selection), response.binding.bindingId == selection.id else { return } |
| 138 | inFlight.insert(id); notice.busy = true; notice.error = nil; notice.held = false |
| 139 | defer { inFlight.remove(id); notice.busy = false } |
| 140 | do { |
| 141 | guard try await session.client.notificationActionsEnabled() else { onRoute?(response.route); dismiss(id); return } |
| 142 | guard current(session, selection) else { return } |
| 143 | let saved = try journal.load(id: id, binding: selection.id) |
| 144 | let stored: Stored? |
| 145 | if let saved { |
| 146 | let value = try JSONDecoder().decode(Stored.self, from: saved) |
| 147 | guard value.response == response else { notice.error = EquipoStrings.text("api.idempotency_conflict"); return } |
| 148 | stored = value |
| 149 | } else { stored = nil } |
| 150 | let write: PendingWrite |
| 151 | var bound: ThinCard? |
| 152 | if let stored { write = stored.write } |
| 153 | else { |
| 154 | if response.intent == .retry { write = try response.pendingWrite() } |
| 155 | else { |
| 156 | if response.intent == .merge { |
| 157 | let snapshot = try await session.client.snapshot() |
| 158 | guard current(session, selection) else { return } |
| 159 | session.apply(snapshot) |
| 160 | } |
| 161 | guard let cardID = response.cardID else { throw EquipoAPIError.undecodable } |
| 162 | let card = try await session.client.notificationCard(cardID) |
| 163 | guard current(session, selection) else { return } |
| 164 | session.applyCard(card) |
| 165 | bound = card |
| 166 | // A placement question resolves a project in the app, never here. |
| 167 | guard !card.isPlacementQuestion else { onRoute?(response.route); dismiss(id); return } |
| 168 | guard card.revision == response.binding.cardRevision, card.isOpen else { |
| 169 | throw EquipoAPIError.server(status: 409, body: APIErrorBody(code: "card_stale", copyKey: "", requestId: "", currentRevision: nil)) |
| 170 | } |
| 171 | if response.intent == .merge { |
| 172 | guard card.kind == "merge", card.taskId == response.taskID, let task = response.taskID else { throw EquipoAPIError.undecodable } |
| 173 | let context = MacTaskContext(session: session, taskID: task) |
| 174 | await context.load() |
| 175 | guard current(session, selection) else { return } |
| 176 | if let error = context.detail.readFailure { notice.error = error; return } |
| 177 | guard context.detail.decision.card?.id == card.id, context.detail.decision.card?.revision == card.revision, |
| 178 | context.detail.decision.canAnswer("merge", note: "") else { throw EquipoAPIError.status(409) } |
| 179 | notice.context = context |
| 180 | await context.detail.answer(card, choice: "merge", note: "") |
| 181 | return |
| 182 | } |
| 183 | guard card.kind == "question" else { throw EquipoAPIError.status(409) } |
| 184 | if response.intent == .question, selectedChoice == nil { notice.card = card; return } |
| 185 | // The person's tap (selectedChoice) wins over the alert's text: a |
| 186 | // held answer may have been edited before it was confirmed. |
| 187 | let choice: String |
| 188 | if let selectedChoice { |
| 189 | guard card.options?.isEmpty != false || card.options?.contains(selectedChoice) == true else { throw EquipoAPIError.undecodable } |
| 190 | choice = selectedChoice |
| 191 | } else if case .answer(let text) = response.intent { |
| 192 | guard card.options?.isEmpty != false else { throw EquipoAPIError.status(409) } |
| 193 | choice = text |
| 194 | } else { throw EquipoAPIError.undecodable } |
| 195 | let body: [String: AnyEncodable] = ["choice": .init(choice), "revision": .init(card.revision), "idempotency_key": .init(id)] |
| 196 | write = PendingWrite(body: try EquipoJSON.encoder.encode(body), ifMatch: card.revision, key: id) |
| 197 | } |
| 198 | guard foreground(notice, card: bound) else { return } |
| 199 | try journal.save(id: id, binding: selection.id, body: JSONEncoder().encode(Stored(response: response, write: write))) |
| 200 | } |
| 201 | guard current(session, selection), foreground(notice, card: nil) else { return } |
| 202 | if response.intent == .retry, let task = response.taskID { try await session.client.retryNotification(task: task, write: write) } |
| 203 | else if let card = response.cardID { let _: Answered = try await session.client.answer(card: card, write) } |
| 204 | else { throw EquipoAPIError.undecodable } |
| 205 | guard current(session, selection) else { return } |
| 206 | try journal.remove(id: id, binding: selection.id) |
| 207 | onRoute?(response.route); dismiss(id) |
| 208 | await session.refresh() |
| 209 | } catch { |
| 210 | guard current(session, selection) else { return } |
| 211 | notice.error = TaskActionFailure.words(error) |
| 212 | let api = error as? EquipoAPIError |
| 213 | if api?.endsSession == true { session.invalidate(); clear(); return } |
| 214 | let definite = api?.status.map { (400..<500).contains($0) && ![401, 403, 408, 425, 429].contains($0) } == true && !(api?.code?.isEmpty ?? true) |
| 215 | notice.canRetry = !definite |
| 216 | if definite { try? journal.remove(id: id, binding: selection.id); notice.card = nil } |
| 217 | notice.uncertain = (try? journal.load(id: id, binding: selection.id)) != nil |
| 218 | if api?.status == 409 { |
| 219 | notice.canRetry = false; notice.card = nil; notice.context = nil |
| 220 | // A stale card may be older than the snapshot window. Fetch its |
| 221 | // current projection for navigation without rebinding this write. |
| 222 | if let id = response.cardID, let card = try? await session.client.notificationCard(id) { |
| 223 | guard current(session, selection) else { return } |
| 224 | session.applyCard(card) |
| 225 | } |
| 226 | guard current(session, selection) else { return } |
| 227 | onRoute?(response.route) |
| 228 | await session.refresh() |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |