import Foundation import Observation import EquipoShareCore #if os(iOS) import UIKit #elseif os(macOS) import AppKit #endif struct NotificationAppState { var active: Bool var protectedData: Bool @MainActor static var current: Self { #if os(iOS) Self(active: UIApplication.shared.applicationState == .active, protectedData: UIApplication.shared.isProtectedDataAvailable) #elseif os(macOS) Self(active: NSApplication.shared.isActive, protectedData: true) #else Self(active: false, protectedData: false) #endif } } @MainActor @Observable final class NotificationNotice: Identifiable { let response: NotificationResponse nonisolated let id: String var error: String? var canRetry = false var busy = false var card: ThinCard? var context: MacTaskContext? var choice = "" /// The person's action waits, in memory only, for their tap: it arrived /// while the app was inactive or the device locked. var held = false /// A journalled request may have reached the server: Try again resends it /// exactly as stored, so the card's inputs stay locked. var uncertain = false init(_ response: NotificationResponse) { self.response = response; id = response.binding.notificationId } } /// Foreground responses only. A saved request is retried only on a response /// delivery or the person's Retry tap, never by refresh or a background timer. @MainActor @Observable final class NotificationDispatcher { private let journal: ActionJournal private var session: EquipoSession? private var selection: NotificationSelection? private var queued: [NotificationResponse] = [] private var inFlight: Set = [] var notices: [NotificationNotice] = [] var onRoute: ((PushRoute) -> Void)? private struct Stored: Codable { let response: NotificationResponse; let write: PendingWrite } private let appState: () -> NotificationAppState init(journal: ActionJournal, appState: @escaping () -> NotificationAppState = { .current }) { self.journal = journal; self.appState = appState } static func live() -> NotificationDispatcher { let folder = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] .appendingPathComponent("Equipo/NotificationActions", isDirectory: true) .appendingPathComponent(Bundle.main.bundleIdentifier ?? "unbundled", isDirectory: true) return NotificationDispatcher(journal: ActionJournal(directory: folder)) } func attach(session: EquipoSession, selection: NotificationSelection?) { let restoring = self.session !== session || self.selection != selection if let old = self.selection, old != selection { clear() } self.session = session; self.selection = selection if restoring, let selection, current(session, selection), let records = try? journal.pending(binding: selection.id) { for data in records { guard let stored = try? JSONDecoder().decode(Stored.self, from: data), stored.response.binding.bindingId == selection.id, !notices.contains(where: { $0.id == stored.response.binding.notificationId }) else { continue } let notice = NotificationNotice(stored.response) notice.canRetry = true; notice.error = EquipoStrings.text("native.share.unconfirmed") notices.append(notice) } } let pending = queued; queued = [] for response in pending { Task { await receive(response) } } } func clear() { session = nil; selection = nil; queued = []; notices = []; inFlight = [] journal.clear() } private func current(_ session: EquipoSession, _ selection: NotificationSelection) -> Bool { self.session === session && self.selection == selection && session.lifetime.isActive && !session.isInvalidated && selection.matches(session.account) } func dismiss(_ id: String) { notices.removeAll { $0.id == id } } func receive(_ response: NotificationResponse) async { guard let session, selection != nil else { if queued.count < 32, !queued.contains(response) { queued.append(response) } return } guard let selection, current(session, selection), response.binding.bindingId == selection.id else { return } if response.intent == .open { onRoute?(response.taskID.map(PushRoute.task) ?? response.route); return } guard !inFlight.contains(response.binding.notificationId) else { return } let notice: NotificationNotice if let existing = notices.first(where: { $0.id == response.binding.notificationId }) { guard existing.response == response else { existing.error = EquipoStrings.text("api.idempotency_conflict"); return } // A held action is sent only by the person's tap, never by a redelivery. guard !existing.held else { return } notice = existing } else { notice = NotificationNotice(response); notices.append(notice) } await run(notice, session: session, selection: selection) } func retry(_ notice: NotificationNotice) async { guard notice.canRetry, let session, let selection, current(session, selection) else { return } // A shown card with nothing journalled sends what the screen shows. if notice.card != nil, !notice.uncertain { await answer(notice, choice: notice.choice); return } await run(notice, session: session, selection: selection) } func answer(_ notice: NotificationNotice, choice: String) async { guard !notice.busy, !notice.uncertain, let card = notice.card, let session, let selection, current(session, selection), card.revision == notice.response.binding.cardRevision, card.isOpen, card.kind == "question", (card.options?.isEmpty != false ? !choice.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty : card.options!.contains(choice)), choice.utf8.count <= 16 * 1024 else { return } notice.choice = choice await run(notice, session: session, selection: selection, selectedChoice: choice) } /// Writes only while the device is unlocked and the app is active in the /// foreground. Otherwise the action is held in memory on its notice, bound /// to the card and revision it read: the typed answer pre-filled, or Try /// again, for the person to confirm with one tap. Nothing reaches disk. private func foreground(_ notice: NotificationNotice, card: ThinCard?) -> Bool { let state = appState() guard state.active && state.protectedData else { if let card, card.revision == notice.response.binding.cardRevision { notice.card = card } if case .answer(let text) = notice.response.intent, notice.choice.isEmpty { notice.choice = text } if notice.response.intent == .retry { notice.canRetry = true } notice.held = true onRoute?(notice.response.route) return false } return true } private func run(_ notice: NotificationNotice, session: EquipoSession, selection: NotificationSelection, selectedChoice: String? = nil) async { let response = notice.response, id = notice.id // The notice's own binding, not only the session's, must be the current one. guard !inFlight.contains(id), current(session, selection), response.binding.bindingId == selection.id else { return } inFlight.insert(id); notice.busy = true; notice.error = nil; notice.held = false defer { inFlight.remove(id); notice.busy = false } do { guard try await session.client.notificationActionsEnabled() else { onRoute?(response.route); dismiss(id); return } guard current(session, selection) else { return } let saved = try journal.load(id: id, binding: selection.id) let stored: Stored? if let saved { let value = try JSONDecoder().decode(Stored.self, from: saved) guard value.response == response else { notice.error = EquipoStrings.text("api.idempotency_conflict"); return } stored = value } else { stored = nil } let write: PendingWrite var bound: ThinCard? if let stored { write = stored.write } else { if response.intent == .retry { write = try response.pendingWrite() } else { if response.intent == .merge { let snapshot = try await session.client.snapshot() guard current(session, selection) else { return } session.apply(snapshot) } guard let cardID = response.cardID else { throw EquipoAPIError.undecodable } let card = try await session.client.notificationCard(cardID) guard current(session, selection) else { return } session.applyCard(card) bound = card // A placement question resolves a project in the app, never here. guard !card.isPlacementQuestion else { onRoute?(response.route); dismiss(id); return } guard card.revision == response.binding.cardRevision, card.isOpen else { throw EquipoAPIError.server(status: 409, body: APIErrorBody(code: "card_stale", copyKey: "", requestId: "", currentRevision: nil)) } if response.intent == .merge { guard card.kind == "merge", card.taskId == response.taskID, let task = response.taskID else { throw EquipoAPIError.undecodable } let context = MacTaskContext(session: session, taskID: task) await context.load() guard current(session, selection) else { return } if let error = context.detail.readFailure { notice.error = error; return } guard context.detail.decision.card?.id == card.id, context.detail.decision.card?.revision == card.revision, context.detail.decision.canAnswer("merge", note: "") else { throw EquipoAPIError.status(409) } notice.context = context await context.detail.answer(card, choice: "merge", note: "") return } guard card.kind == "question" else { throw EquipoAPIError.status(409) } if response.intent == .question, selectedChoice == nil { notice.card = card; return } // The person's tap (selectedChoice) wins over the alert's text: a // held answer may have been edited before it was confirmed. let choice: String if let selectedChoice { guard card.options?.isEmpty != false || card.options?.contains(selectedChoice) == true else { throw EquipoAPIError.undecodable } choice = selectedChoice } else if case .answer(let text) = response.intent { guard card.options?.isEmpty != false else { throw EquipoAPIError.status(409) } choice = text } else { throw EquipoAPIError.undecodable } let body: [String: AnyEncodable] = ["choice": .init(choice), "revision": .init(card.revision), "idempotency_key": .init(id)] write = PendingWrite(body: try EquipoJSON.encoder.encode(body), ifMatch: card.revision, key: id) } guard foreground(notice, card: bound) else { return } try journal.save(id: id, binding: selection.id, body: JSONEncoder().encode(Stored(response: response, write: write))) } guard current(session, selection), foreground(notice, card: nil) else { return } if response.intent == .retry, let task = response.taskID { try await session.client.retryNotification(task: task, write: write) } else if let card = response.cardID { let _: Answered = try await session.client.answer(card: card, write) } else { throw EquipoAPIError.undecodable } guard current(session, selection) else { return } try journal.remove(id: id, binding: selection.id) onRoute?(response.route); dismiss(id) await session.refresh() } catch { guard current(session, selection) else { return } notice.error = TaskActionFailure.words(error) let api = error as? EquipoAPIError if api?.endsSession == true { session.invalidate(); clear(); return } let definite = api?.status.map { (400..<500).contains($0) && ![401, 403, 408, 425, 429].contains($0) } == true && !(api?.code?.isEmpty ?? true) notice.canRetry = !definite if definite { try? journal.remove(id: id, binding: selection.id); notice.card = nil } notice.uncertain = (try? journal.load(id: id, binding: selection.id)) != nil if api?.status == 409 { notice.canRetry = false; notice.card = nil; notice.context = nil // A stale card may be older than the snapshot window. Fetch its // current projection for navigation without rebinding this write. if let id = response.cardID, let card = try? await session.client.notificationCard(id) { guard current(session, selection) else { return } session.applyCard(card) } guard current(session, selection) else { return } onRoute?(response.route) await session.refresh() } } } }